Recursion for a certain amount of time
October 20, 2009by Lee Spector (lspector)
I was asked about whether it was possible to use the time to terminate an otherwise endless recursion, and I thought the answer might interest other people as well:
—
Sure. There are a couple of ways.
If you are flexible enough in your interpretation of “time” and “how long it’s been running” then you could do something very simple by setting up a step counter, something like this:
(define ticks 0) (define my-function (lambda () (unless (>= ticks 40) (print '*) ;; or whatever else you want to do (set! ticks (+ ticks 1)) (my-function)))) (my-function)
If you really mean clock time then you can use the function current-seconds. This takes no arguments and it “Returns the current time in seconds. This time is always an exact integer based on a platform-specific starting date (with a platform-specific minimum and maximum value).”
The upshot of this is that (current-seconds) will return a big number but the differences between its values in subsequent calls will reflect the number of seconds called. So you could do something like this:
(define starting-time (current-seconds)) (define print-stuff-for-5-seconds (lambda () (print '*) (unless (> (- (current-seconds) starting-time) 4) (print-stuff-for-5-seconds)))) (print-stuff-for-5-seconds)
If you need more resolution there’s also (current-milliseconds).