Python 时间变量没有改变

Python time variable is not changing

我修改了一些在 Whosebug 上找到的 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() 时它应该得到一个新值。

它不起作用的原因是因为在 start 中,startTime 是一个 local 变量。如果你想更新 global 变量,你需要明确地告诉 python:

def start():
    global startTime  # tell python to work with `startTime` in the global scope.
    atexit.register(stop)
    print(line,"Start time measurement")
    startTime = clock()
    print("new start time:", startTime)

但是请注意,99% 的情况下,当您使用 global 语句时,可能有更好的选择。在不知道您的确切用例的情况下,很难给出完美的建议。但是,我可能会在这里考虑上下文管理器:

import contextlib
from time import clock

line = "="*10 + ">>>"

def secondsToStr(s):
    return "{0}.{1}ms".format(round(s*1000), round(s*1000000))

@contextlib.contextmanager
def timer():
    start = clock()
    try:
        yield None
    finally:
        stop = clock()
        print(line, "Ellapsed time:", secondsToStr(elapsed))

您可以按如下方式使用它:

with timer():
    do_something()
    do_something_else()

在函数 return 之后,您将打印出这两个函数的组合运行时间。与您的原件一样,如果发生异常,它仍会打印。

On Unix, return the current processor time as a floating point number expressed in seconds. The precision, and in fact the very definition of the meaning of “processor time”, depends on that of the C function of the same name, but in any case, this is the function to use for benchmarking Python or timing algorithms.

这意味着 time.clock() 测量了从您的进程开始的时间。如果你想测量挂钟时间,你可以使用 time.time()