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

I can see that time.clock () on Windows starts a timer when called for the first time and returns the time elapsed since the first calls are called after that. I read that the only way to restart the clock is to start a new process.

Start and kill threads that should restart time.clock ()? It doesn't seem to work right now. If not, is this the only solution to rerun the entire executable?

+2


a source to share


2 answers


The thread is not a process, so no. (As a side note, you can't kill a thread in Python, you can ask it to quit. Killing threads with other means, where such means even exist, will likely leave Python in a bad state.)



The question is why do 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 it time.time()

doesn't fit, you just need to subtract the first point from the second point. No reboot required. I would recommend using time.time()

it unless you really care that the granularity difference is small, since it time.time()

works the same on all platforms, unlike time.clock()

.

+4


a source


If you want to use the clock, you can reset to a precision time.clock()

that is higher than that time.time()

just because the float of the second is larger (an almost imperceptible difference), for measuring the time elapsed when you run some code, you can try this:

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

      

Yo can also try decorating a function 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 that, you can define your function with a decorator:

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

      

Or just call the function with a decorator:

duration(myFun)(*args)

      

0


a source







All Articles