A relatively foolish but maybe satisfactory solution would be to just set a timer and check it every loop iteration:
import time
def foo(txt):
best_value=-1
curr_time = time.time()
for word in txt:
if value(word)>best_value:
best_value=value(world)
if time.time() - curr_time > 60:
break
return best_value
The big disadvantage here is a lot of compute that's wasted on checking, where we have to do a syscall to retrieve the time.
We could alleviate this by just checking every 1000 words (for example), like so:
import time
def foo(txt):
best_value=-1
curr_time = time.time()
for i, word in enumerate(txt):
if value(word)>best_value:
best_value=value(world)
if i % 1000 == 0 and time.time() - curr_time > 60:
break
return best_value
This would just do the much cheaper check of i % 1000
and it would short circuit before computing time.time() - curr_time > 60
.
This is probably more than good enough, but if you want more, here's another possible angle.
Update some shared memory between two separate processes, where one process does the computation and updates some shared memory, and the other process is responsible for sleeping for 60 seconds then killing the other process.
This is probably very useful if you choose to go down that route.