tags:

views:

26

answers:

2

Hi!

I want to run a part of my loop for a certain time: 60 seconds. Afterwards I set a boolean flag and continue at another point. Does Python have something like a stopwatch? Maybe this is OS specific: it's targeted against a Linux env.

Sleeping a couple of seconds is easy... no question. ;) I want the opposite.

+1  A: 

You could use the time.time() method:

import time
endtime = time.time() + 60
while time.time() < endtime:
    # do something

Note - you probably don't want to use time.clock() as this measures CPU time rather than wall time.

Dave Webb
A: 

You could use time.time() to set the begin of the loop, and later check if the passed time is greater than 60 seconds. But then you'll have a problem if the clock changes during the loop (very rare case) - so you should check for negative differences, too.

import time

begin = time.time()

for something:
    # do something

    if not (begin <= time.time() <= begin + 60):
        break

As far as I know, Python does not include a stop watch class like in C#, for example.

AndiDog