1 | initial version |
One way is to use alarm
and AlarmInerrupt
:
sage: from cysignals.alarm import alarm, AlarmInterrupt, cancel_alarm
If computation takes more than 5 seconds, computation is stopped:
sage: try:
....: alarm(5)
....: factor(2^1000-1)
....: except AlarmInterrupt:
....: print('opps, timed out!')
....: else:
....: cancel_alarm()
....:
opps, timed out!
If computation takes less than 5 seconds, it is not stopped:
sage: try:
....: alarm(5)
....: factor(2^100-1)
....: except AlarmInterrupt:
....: print('opps, timed out!')
....: else:
....: cancel_alarm()
....:
3 * 5^3 * 11 * 31 * 41 * 101 * 251 * 601 * 1801 * 4051 * 8101 * 268501
It is important to cancel the alarm if the computation succeeds (as done above in the else
clause) or otherwise the AlarmInterrupt
will be raised later on.
2 | No.2 Revision |
One way is to use alarm
and AlarmInerrupt
:
sage: from cysignals.alarm import alarm, AlarmInterrupt, cancel_alarm
If computation takes more than 5 seconds, computation is stopped:
sage: try:
....: alarm(5)
....: factor(2^1000-1)
....: except AlarmInterrupt:
....: print('opps, timed out!')
....: else:
....: cancel_alarm()
....:
opps, timed out!
If computation takes less than 5 seconds, it is not stopped:
sage: try:
....: alarm(5)
....: factor(2^100-1)
....: except AlarmInterrupt:
....: print('opps, timed out!')
....: else:
....: cancel_alarm()
....:
3 * 5^3 * 11 * 31 * 41 * 101 * 251 * 601 * 1801 * 4051 * 8101 * 268501
It is important to cancel the alarm if the computation succeeds (as done above in the else
clause) or otherwise the AlarmInterrupt
will be raised later on.
EDIT: In some cases including the question asked here, you may need to also catch KeyboardInterrupt
exception:
#!/usr/bin/env sage
from sage.all import *
from cysignals.alarm import alarm, AlarmInterrupt, cancel_alarm
var('x a b')
def doTheIntegration():
integrand = tan(x)/(a^3+b^3*tan(x)^2)^(1/3)
fricas.setSimplifyDenomsFlag(fricas.true)
anti=integrate(integrand,x,algorithm="fricas")
return anti
try:
alarm(20)
anti = doTheIntegration()
except (AlarmInterrupt,KeyboardInterrupt):
print("Timed out")
else:
print("Completed OK, anti=",anti)
cancel_alarm()