【问题标题】:benchmarking python script reveals mysterious time delays基准测试python脚本揭示了神秘的时间延迟
【发布时间】:2011-07-02 10:07:34
【问题描述】:

我有两个模块:moduleParent 和 moduleChild

我在 moduleParent 中做这样的事情:

import moduleChild

#a bunch of code

start = time.time()
moduleChild.childFunction()
finish = time.time()
print "calling child function takes:", finish-start, "total seconds"

#a bunch of code

我在 moduleChild 中做这样的事情:

def childFunction():
    start = time.time()
    #a bunch of code
    finish = time.time()
    print "child function says it takes:", finish-start, "total seconds"

输出如下所示:

calling child function takes: .24 total seconds
child function says it takes: 0.0 total seconds

所以我的问题是,这些额外的 0.24 秒是从哪里来的?

感谢您的专业知识。

#

这里是“childFuntion”的实际代码。真的不应该花 0.24 秒。

 def getResources(show, resourceName='', resourceType=''):
   '''
   get a list of resources with the given name

   @show: show name
   @resourceName: name of resource
   @resourceType: type of resource
   @return: list of resource dictionaries
   '''

   t1 = time.time()

   cmd = r'C:\tester.exe -cmdFile "C:\%s\info.txt" -user root -pwd root'%show
   cmd += " -cmd findResources -machineFormatted "

   if resourceName:
       cmd += '-name %s'%resourceName

   if resourceType:
       cmd += '_' + resourceType.replace(".", "_") + "_"

   proc=subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
   output = proc.stdout.read()
   output = output.strip()

   resourceData = output.split("\r\n")
   resourceData = resourceData[1:]

   resourceList = []
   for data in resourceData:
       resourceId, resourceName, resourceType = data.split("|")
       rTyp = "_" + resourceType.replace(".", "_") + "_"
       shot, assetName = resourceName.split(rTyp)
       resourceName = assetName
       path = '//projects/%s/scenes/%s/%s/%s'%(show, shot, resourceType.replace(".", "/"), assetName)
       resourceDict = {'id':resourceId, 'name':resourceName, 'type':resourceType, 'path':path }
       resourceList.append(resourceDict)

   t2 = time.time()
   print ("     ", t2 - t2, "seconds")


   return resourceList

【问题讨论】:

  • 这是准确的输出吗?线条不是颠倒了吗?
  • 这不是确切的输出,不。这只是一个简化的例子。
  • 你有你的答案t2 - t2 = 0
  • 天哪。我是个白痴。谢谢大家。

标签: python time benchmarking


【解决方案1】:

编辑 2:我刚刚注意到子函数中有一个错字,打印语句中有 t2 - t2

忽略以下:

调用函数本身有开销(设置堆栈空间、保存局部变量、返回等)。结果表明您的函数非常简单,以至于设置函数调用所用的时间比运行代码本身要长。

编辑:另外,调用计时器以及平面广告开销。现在我想起来了,调用 print 可能占了 0.24 秒的很多时间。 IO 很慢。

【讨论】:

  • childFunction 是做什么的?很难想象在任何合理的系统上花费 0.24 秒的函数调用的开销,当然对于可以在 0.0 秒内完成的函数。我猜你可能会删除最后一个为垃圾收集器释放大量对象的引用。
  • 更不用说孩子打印花了多长时间,这不包括在它说的时间里。 :-)
  • @MRAB,是的,但打印语句不应花费 0.24 秒!
  • 查看我的最新编辑,您在子函数的打印语句中有错字,t2 - t2 应该是 t2 - t1
【解决方案2】:

您无法通过运行一次函数来衡量函数的时间,尤其是运行时间如此短的函数。影响时间的因素有很多,其中最重要的是您在系统上运行的其他进程。

这样的事情我可能至少会运行几百次。查看timeit 模块。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-23
    • 2021-03-15
    • 2018-04-17
    • 2013-07-13
    • 1970-01-01
    • 2015-12-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多