views:

429

answers:

2

I want to see how long a function takes to run. What's the easiest way to do this in PLT-Scheme? Ideally I'd want to be able to do something like this:

> (define (loopy times)
  (if (zero? times)
      0
      (loopy (sub1 times)))) 
> (loopy 5000000)
0                      ;(after about a second)
> (timed (loopy 5000000))
Took: 0.93 seconds
0
>

It doesn't matter if I'd have to use some other syntax like (timed loopy 5000000) or (timed '(loopy 5000000)), or if it returns the time taken in a cons or something.

+3  A: 

Found it...

From the online documentation:

  • (time-apply proc arg-list) invokes the procedure proc with the arguments in arg-list. Four values are returned: a list containing the result(s) of applying proc, the number of milliseconds of CPU time required to obtain this result, the number of ``real'' milliseconds required for the result, and the number of milliseconds of CPU time (included in the first result) spent on garbage collection.

Example usage:

> (time-apply loopy '(5000000))
(0)
621
887
0
Claudiu
+3  A: 

The standard name for timing the execution of expressions in most Scheme implementations is "time". Here is an example from within DrScheme.

(define (loopy times) (if (zero? times) 0 (loopy (sub1 times))))

(time (loopy 5000000)) cpu time: 1526 real time: 1657 gc time: 0 0

If you use time to benchmark different implementations against each other, remember to use mzscheme from the command line rather than benchmarking directly in DrScheme (DrScheme inserts debug code in order to give better error messages).

soegaard