yarden
yarden

Reputation: 31

how to stop a func from running and return a value after one minute?

I would like to call a func and stop it from running after one minute, returning a value. i have a code that looks similar to that:

def foo(txt):
   best_value=-1
   for word in txt:
       if value(word)>best_value:
           best_value=value(world)
    return best_value

i would like to stop running after one minute and return best_value. thanks for your help.

Upvotes: 2

Views: 588

Answers (2)

Raymond Hettinger
Raymond Hettinger

Reputation: 226346

If you want to decouple the timing code from the business logic and to keep the overhead to a minimum, an easy way is to use a global variable in the code to tell it when to stop running:

time_out = False

def foo(txt):
   best_value=-1
   for word in txt:
       if value(word)>best_value:
           best_value=value(world)
       if time_out:
           break
    return best_value

Then use a separate function tied to use a Timer to stop it:

def send_stop():
    global time_out
    time_out = True

Timer(60.0, send_stop).start() 
best_value = foo(corpus)

Upvotes: 1

alex
alex

Reputation: 86

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.

Upvotes: 2

Related Questions