我修改了一些在stackoverflow上发现的here代码,但是我得到了一些奇怪的行为。有人能看出我的错误吗?在import atexit
from time import clock
line = "="*10 + ">>>"
def secondsToStr(s):
return "{0}.{1}ms".format(round(s*1000), round(s*1000000))
##
# @brief Starts a timer. If the program crashes, the end function will be called anyway.
def start():
atexit.register(stop)
print(line,"Start time measurement")
startTime = clock()
print("new start time:", startTime)
##
# @brief Needs to be called after start(). Prints the time passed since start() was called.
def stop():
end = clock()
elapsed = end-startTime
print(startTime, end) # Inserted for debugging
print(line, "Ellapsed time:", secondsToStr(elapsed))
atexit.unregister(stop)
def now():
return secondsToStr(clock())
startTime = clock()
其思想是调用start()和stop()来测量程序在这两个调用之间花费的时间。奇怪的是,startTime没有改变。因此,stop()的每个调用都给出了自start()第一次调用以来的过去时间。以下是输出示例:
^{pr2}$
为什么startTime永远不变?它应该在每次调用start()时获得一个新值。在