How to stop code after a given time
My question is the following: sometimes a computation runs too long, and I would rather for it to stop automatically, and move on to the next computation (in the best possible world keep a list of the cases that were skipped).
So I wanted to implement the solution to this (essentially) identical question:
https://stackoverflow.com/questions/1...
However in my case the function "foo" uses some functionalities of GAP. This apparently causes a crash:
** Gap crashed or quit executing '__SAGE_LAST__:="__SAGE_LAST__";;AllSmallGroups(\$sage1);;' ** Restarting Gap and trying again
The crash happens immediately on the first call of the GAP function. Is there any way to avoid this?
EDIT
The suggestion with alarm
did not work for me (maybe it has to with my implementation). Basically the first interruption works correctly (after 20 seconds), then follows five minutes where nothing happens, after these five minutes the second iteration of the for loop begins, this second iteration is
from cysignals.alarm import alarm, AlarmInterrupt, cancel_alarm for i in range(0,10): try: alarm(20) print("Began computation at", time.localtime()) foo(i) except AlarmInterrupt: print("Timed out with ", i, "at", time.localtime()) cancel_alarm() ## the presence or absence of this line does not change anything else: print("Completed with", i, "at", time.localtime()) cancel_alarm()
I think there was something like
alarm
andAlarmInterrupt
. Maybe you can use them withtry
andexcept
.@tolga thanks for the suggestion, but this used to cause strange dumps which eventually led to kernel death and stops the further computations. This basically misses the whole point (because I want the computation on other cases to go on, and not the kernel to die before it at least tried the other cases. Basically Alarm does not stop properly the computations... or at least it used to.
@tolga I tried it and it doesn't work. After the first alarm() all further alarms are ignored. Also the kernel died after I did the KeyboardInterrupt (but that could be unrelated). Perhaps I misused the alarm code, so I edited it into the question...
Check this out: https://ask.sagemath.org/question/10112
As for
alarm
, it needs to be reset after each use by callingalarm()
without argumentsalarm(0)
, which will make it available for using again.