我正在寻找一个宏,如果表达式花费的时间超过X秒才能完成,则该宏将引发异常。
最佳答案
这个问题在这里有更好的答案:
Executing a function with a timeout
期货救助!
user=> (let [f (future (reduce * (range 1 1001)))]
(.get f 1 java.util.concurrent.TimeUnit/MILLISECONDS))
java.util.concurrent.TimeoutException (NO_SOURCE_FILE:0)
并使其宏:
(defmacro time-limited [ms & body]
`(let [f# (future ~@body)]
(.get f# ~ms java.util.concurrent.TimeUnit/MILLISECONDS)))
因此,您可以执行以下操作:
user=> (time-limited 1 (reduce * (range 1 1001)))
java.util.concurrent.TimeoutException (NO_SOURCE_FILE:0)
user=> (time-limited 1 (reduce * (range 1 101)))
93326215443944152681699238856266700490715968264381621468592963895217599993229915
608941463976156518286253697920827223758251185210916864000000000000000000000000