开发者

Python time.clock() - reset clock value with threads

开发者 https://www.devze.com 2022-12-27 05:17 出处:网络
I see time.clock() on Windows \'starts\' a timer when called for the first time, and returns elasped time since the first call for calls after that. I read that the only way to restart the clock开发者

I see time.clock() on Windows 'starts' a timer when called for the first time, and returns elasped time since the first call for calls after that. I read that the only way to restart the clock开发者_如何学JAVA is to start a new process.

Is starting and killing threads supposed to restart the time.clock() as well? It doesn't seem to be working right now. If not, is the only solution to re-launch the entire executable?


A thread is not a process, so, no. (As a minor point, you can't kill a thread in Python, you can only ask it to exit. Killing threads through other means, where such means even exist, is likely to leave Python in a bad state.)

The question is why you want to reset the timer, and also why you are using time.clock(). If you care about the elapsed time between two points at such a high granularity that time.time() is not suitable, you'll just have to subtract the first point from the second point. No resetting required. I would recommend just using time.time() unless you really care about that tiny bit of difference in granularity, as time.time() works the same way on all platforms, contrary to time.clock().


Leaving threads apart if you want a clock you can reset with the precision of time.clock() which is higer than the one of time.time() just because the float of the second one is bigger (almost imperceptible difference), for measuring the lapse of time past while running some code you can try this:

t0 = time.clock()
... do something
print('Running time:', time.clock()-t0)

Yo can also try a function decoration for this:

def duration(code):
    def f(*args):
        t0 = time.clock()
        bar = code(*args)
        print('Running time:', time.clock()-t0)
        return bar
    return f

After this you can define your function with the decorator:

@duration
def myFun(*args):
    ... do something

Or just call the function with the decorator:

duration(myFun)(*args)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号