2

我看到 Windows 上的 time.clock() 在第一次调用时会“启动”一个计时器,并返回自第一次调用之后经过的时间。我读到重新启动时钟的唯一方法是启动一个新进程。

启动和终止线程是否也应该重新启动 time.clock() ?它现在似乎不起作用。如果不是,是重新启动整个可执行文件的唯一解决方案吗?

4

2 回答 2

4

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().

于 2010-04-19T19:55:10.343 回答
0

如果你想要一个时钟,你可以将线程分开,你可以重置它的精度time.clock()高于一个,time.time()因为第二个的浮点数更大(几乎无法察觉的差异),用于在运行一些代码时测量过去的时间流逝可以试试这个:

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

哟也可以为此尝试功能装饰:

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

在此之后,您可以使用装饰器定义您的函数:

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

或者只是用装饰器调用函数:

duration(myFun)(*args)
于 2013-04-20T14:28:38.707 回答