Python在不同位置/类中创建时间戳以记录功能块运行时间



我知道如何创建基本时间戳:

t1 = time.time()
# program runs runs
t2 = time.time()
dt = t2 - t1

我的问题是,该程序是一个很大的巨大质量,它起作用,但其中包含数千条线和绕组类,方法呼叫,函数。

总结一下,这就是我要实现的目标:

  1. 我想在一个班级的中间种植T1,
  2. 一些Func称此类为此类,然后是其他模块的另一个类,等等,
  3. 在其他一些课程的结尾,我想种植一个T2,
  4. 然后在最后,我想输出一个dt = t2 - t1
  5. 我对全局变量有所了解,但不确定是否对交叉模块可行,我的意思是T1可能来自ABC.Py,T2可能来自123.Py,是否有可能?

一个想法是创建一个具有全局变量的模块,这样您就不会污染名称空间太多。

这是mytimer.py:

import time
TIMER = None
def start():
    global TIMER
    TIMER = time.time()
def stop(msg=None):
    global TIMER
    msg = msg or "TIMER"
    if TIMER:
        print('%s -- %s' % (msg, time.time() - TIMER))
    else:
        print 'ERROR: TIMER is not set'

然后,假设您在module1.py中启动计时器:

import mytimer
def somefun():
    mytimer.start()
somefun()

您可以看到在另一个模块中调用mytimer.stop()时花了多少时间,这是module2.py:

import mytimer
import module1
mytimer.stop(msg="Timer from module1:")
# restart timer
mytimer.start()
# .. do something here
# and then get timer with specific message
mytimer.stop(msg='Finished at')

这应该导致:

$ python module2.py 
Timer from module1 -- 3.81469726562e-06 sec
Finished at -- 9.53674316406e-07 sec

最新更新