Python时间变量没有变化

时间:2016-05-13 22:01:36

标签: python python-3.x clock timing

我在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()来衡量程序在这两个calles之间的时间。奇怪的是,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()时都应该获得一个新值。

2 个答案:

答案 0 :(得分:1)

它不起作用的原因是因为在start内,startTime本地变量。如果要更新全局变量,则需要明确告诉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()

在函数返回后,您将获得打印的两个函数的组合运行时。与原件一样,如果发生异常,仍会打印。

答案 1 :(得分:-1)

  

在Unix上,将当前处理器时间返回为以秒为单位的浮点数。精确度,实际上是“处理器时间”含义的定义,取决于同名C函数的精度,但无论如何,这是用于对Python或时序算法进行基准测试的函数。 p>

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