在python中测量时间的不寻常结果

时间:2013-04-01 04:55:57

标签: python performance time

这是我的秒表班

import time

class StopWatch:

    def __init__(self, tag="", startTime=time.time(), elapsedTime=-1):
        self._tag=tag
        self._elapsedTime=elapsedTime
        self._startTime=startTime

    # other codes here............#

    def stop(self, tag=None):
        if tag is not None:
            self._tag = tag
        self._elapsedTime = time.time() - self._startTime
        return self

    def getStartTime(self):
        return self._startTime

秒表测试文件是:

import unittest
import time
from metric.StopWatch import StopWatch

class StopWatchTest(unittest.TestCase):

    def test_stopwatch(self):
        now=time.time()
        print "now:%f" % now

        stopwatch=StopWatch("firstHook")
        print "start time:%r" % stopwatch.getStartTime()
        self.assertTrue(stopwatch.getStartTime()>now, "start time is wrong")

我得到的是错误:

now:1364791630.047630
start time:1364791629.158797

...

AssertionError: start time is wrong

稍后要执行的代码显示较早的时间。这背后的原因是什么?

2 个答案:

答案 0 :(得分:3)

原因是这一行:

def __init__(self, tag="", startTime=time.time(), elapsedTime=-1):

在Python解释器到达时进行评估(因为尽管名称它实际上编译代码,但尽管是字节代码)。因此,在定义类时设置startTime,而不是在调用__init__时设置。

将其更改为:

def __init__(self, tag="", start_time=None, elapsed_time=-1):
    if start_time is None:
        start_time = time.time()
    self._tag=tag
    self._elapsed_time=elapsed_Time
    self._start_time=start_time

答案 1 :(得分:3)

默认参数仅评估一次。

def __init__(self, tag="", startTime=time.time(), elapsedTime=-1):
    self._tag=tag
    self._elapsedTime = elapsedTime
    self._startTime = startTime

要修复,我们需要明确检查默认值并在函数体中对它们进行评估:

def __init__(self, tag="", startTime=None, elapsedTime=-1):
    self._tag=tag
    self._elapsedTime = elapsedTime
    if startTime is None:
        startTime = time.time()
    self._startTime = startTime