I've been searching a way to stop a function after X seconds on lisp and I haven't found anything and have no ideia how to do it.
It's for finding heuristic weights on a function for a tetris game and if the weights are bad the program will run for more than 30 seconds and I don't want that. Any ideias, please?
Common Lisp has a library for that: Trivial Timeout.
The API is simple: Trivial Timeout API.
One possible way is to pass down an "expiry timer" and check if the current time is later than the expiry time in every iteration and, if it has expired, return the best solution so far. The standard function get-universal-time
may be useful, but gives you a minimal granularity of seconds. A rough skeleton below. If you use recursive functions, simply pass the expiry timer down with whatever else you pass down and use that as your first recursion termination criterion.
(defun do-tetris-stuff (tetris-weights expiry-time)
(let ((best-solution nil))
(loop while (and (<= expiry-time (get-universal-time))
(not (good-enough-p best-solution)))
do (let ((next-solution ...))
(when (better-than-p next-solution best-solution)
(setf best-solution next-solution))))
best-solution))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With