Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Abort function after X seconds - lisp

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?

like image 846
Lidia Freitas Avatar asked Dec 02 '22 15:12

Lidia Freitas


2 Answers

Common Lisp has a library for that: Trivial Timeout.

The API is simple: Trivial Timeout API.

like image 84
Rainer Joswig Avatar answered Jan 30 '23 20:01

Rainer Joswig


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))
like image 33
Vatine Avatar answered Jan 30 '23 21:01

Vatine