Skip to main content
 首页 » 编程设计

Python:如何测量等待 I/O 所花费的时间

2024年10月25日10zhujiabin

我对我的 Python 脚本中的函数使用了 profile 来获取它们的执行时间,并且我使用了 Unix time 命令来获取 real,user 和 sys 脚本总体时间,但我找不到如何测量 Python 中等待 I/O 所花费的时间。

在我的脚本中查询各种数据库,我可以测量发送和接收信息所花费的时间吗?

请您参考如下方法:

你可以使用 Decorator这样可以让您测量专用方法的执行时间:

import time                                                 
 
def measure_time(f): 
 
  def timed(*args, **kw): 
    ts = time.time() 
    result = f(*args, **kw) 
    te = time.time() 
 
    print '%r (%r, %r) %2.2f sec' % \ 
          (f.__name__, args, kw, te-ts) 
    return result 
 
return timed 

你可以这样使用它:

  @measure_time 
  def foo(): 
        #content of function  

注意 f.__name__ 返回函数的名称! (在本例中为“foo”)