【发布时间】:2016-05-13 22:01:36
【问题描述】:
我修改了一些在 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() 以来的过去时间。这是一个示例输出:
==========>>> Start time measurement
new start time: 0.285078
Doing work
0.231932 1.766478
==========>>> Ellapsed time: 1535.1534546ms
==========>>> Start time measurement
new start time: 1.766624
More work
0.231932 1.975752
==========>>> Ellapsed time: 1744.1743820ms
==========>>> Start time measurement
new start time: 1.975821
More work
0.231932 1.976301
==========>>> Ellapsed time: 1744.1744369ms
为什么startTime 永远不会改变?每次调用 start() 时,它都应该获得一个新值。
【问题讨论】:
-
你知道什么是局部变量吗?
标签: python python-3.x clock timing