wishi
wishi

Reputation: 7387

Time actions in Python

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.

Upvotes: 1

Views: 8187

Answers (2)

AndiDog
AndiDog

Reputation: 70148

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.

Upvotes: 0

David Webb
David Webb

Reputation: 193716

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.

Upvotes: 2

Related Questions