【问题标题】:Python time variable is not changingPython时间变量没有改变
【发布时间】: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


【解决方案1】:

它不起作用的原因是因为在start 内部,startTime 是一个本地 变量。如果你想更新 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()

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

【讨论】:

  • 谢谢,您使用 contextmanager 的解决方案非常干净
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-30
    • 2014-12-02
    • 1970-01-01
    • 1970-01-01
    • 2020-07-09
    • 2023-04-02
    • 2012-08-20
    • 1970-01-01
    相关资源
    最近更新 更多