Python:如何度量等待I/O的时间?

Python:如何度量等待I/O的时间?,python,Python,我在Python脚本中对函数使用了profile来获取它们的执行时间,我还使用Unix time命令来获取脚本的real、user和sys时间,但我找不到如何度量在Python中等待I/O所花费的时间 在我的脚本中,我可以查询各种数据库,我可以测量发送和接收信息所需的时间吗?您可以使用这样的方法来测量专用方法的执行时间: import time def measure_time(f): def

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

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

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

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.\uuuuu name\uuuuu
返回函数名!(在本例中为“foo”)

如果您只想测量I/O上花费的时间(忽略CPU上花费的时间),您可以编写一个自定义计时器函数:

import os

def io_timer():
    timing = os.times()
    return timing.elapsed - (timing.system + timing.user)
并将其传递到
cProfile

import cProfile, pstats

def profile_io_time(f, *args, **kwargs):
    prof = cProfile.Profile(io_timer)
    prof.runcall(f, *args, **kwargs)
    result = pstats.Stats(prof)
    result.sort_stats("time")
    result.print_stats()
您可以这样使用它:

from urllib.request import urlopen

profile_io_time(lambda: urlopen("https://google.com").read())

非常感谢你的帮助,我现在知道大部分时间都在往哪里走了!:)