【问题标题】:time.clock(), Odd result when used inside function-definitiontime.clock(),在函数定义中使用时的奇数结果
【发布时间】:2014-10-11 06:47:47
【问题描述】:

使用以下代码(Python 3.3.x、WinXp):

## debug function in a general/personal debug include file.
def timer_compare(time1, time2='', note='@', time3=time.clock()):
    print('time1',time1)
    time2 = time.clock() ## same as the function-passed time.clock() (just a little later)
    print('time2',time2)
    print('time3',time3)
    exit(321)

主代码文件中使用的调用者代码:

time0 = time.clock()
## <other unrelated code.>
timer_compare(time0, time.clock())

我得到以下输出:

time1 0.0445(snip)
time2 0.0445(snip)
time3 0.0000043(snip) <- 4.385582001116343e-06

time3 这里似乎有办法降低数字。 (它看起来像是从一个刚刚创建的计时器案例中拉出来的。)

这里发生了什么/我错过了什么?

  • 我知道 time.time() 通常比 time.clock() 更受欢迎/建议,以及为什么。

【问题讨论】:

    标签: python python-3.x windows-xp


    【解决方案1】:

    函数默认值是在定义时创建的,而不是在调用时创建的。 timer_compare 函数是一个对象,在创建它并存储为该对象的属性时会评估默认值。

    由于您的函数是在您的模块被导入时创建的(或者当您的顶级脚本首次被 Python 加载时),time.clock() 的值将非常低。

    改用哨兵:

    def timer_compare(time1, time2='', note='@', time3=None):
        if time3 is None:
            time3 = time.clock()
    

    【讨论】:

    • 啊哈。我想我明白了它的要点。是时候探索文档了。谢谢(Bedankt,naam genoot。:))
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-22
    相关资源
    最近更新 更多