Skip to content

TimeConstrained ​

Evaluates expr, but aborts after t seconds and returns failexpr.

✓ checked against that system · ! checked, with disagreements (hover a chip)Wolfram LanguageTimeConstrained!
TimeConstrained(expr, t)aborts to Aborted past tt seconds.
TimeConstrained(expr, t, failexpr)aborts to failexpr\mathit{failexpr} instead.
Typed signatures
TypePackageApplies
(any, real, any?) time -> anyevaluationalways

Domain: Controlling evaluation

Details
  • A deadline only interrupts code that LOOKS at it: compute-engine's own loops (Sum, Pollard's rho inside FactorInteger, …) cooperate, so a computation built entirely from them can actually be cut off mid-flight.
  • Without a failexpr the answer is the symbol Aborted; our names never carry a $ prefix, so this is Wolfram's $Aborted, which the Wolfram transpiler writes at the boundary.
  • Held: expr and failexpr are not evaluated until it is known which one is wanted.
  • There is also an evaluateAsync route, used automatically inside an async evaluation (e.g. a notebook cell): the caller's own AbortSignal and the timeout race each other, and only the timeout converts to failexpr — the caller's own cancellation propagates.

Examples

Basic #

Finishes well inside the deadline, so the value passes through unchanged

live ↗
InTimeConstrained(∑k=110k,1)\mathrm{TimeConstrained}(\sum_{k=1}^{10}k, 1)Out5555

Factoring a 30-digit semiprime outruns a 50 ms deadline — compute-engine's own rho loop checks it and gives up

live ↗
InTimeConstrained(FactorInteger(1 001 000 000 000 040 037 000 000 000 111),0.05)\mathrm{TimeConstrained}(\mathrm{FactorInteger}(1\,001\,000\,000\,000\,040\,037\,000\,000\,000\,111), 0.05)OutAborted\mathrm{Aborted}

A custom failexpr replaces the default Aborted

live ↗
InTimeConstrained(FactorInteger(1 001 000 000 000 040 037 000 000 000 111),0.05,−1)\mathrm{TimeConstrained}(\mathrm{FactorInteger}(1\,001\,000\,000\,000\,040\,037\,000\,000\,000\,111), 0.05, -1)Out−1-1
Scope #

An infinite time limit imposes no constraint

live ↗
InTimeConstrained(1+2,∞)\mathrm{TimeConstrained}(1+2, ∞)Out33
Properties #

failexpr is held: it is never evaluated when expr finishes in time

live ↗
InTimeConstrained(2+3,1,10)\mathrm{TimeConstrained}(2+3, 1, \frac{1}{0})Out55
About
Examples5
Checked againstWolfram Language 3 agree2 differ
CrosswalkWolfram Language