2011-07-02 23 views
0

我有两个模块:moduleParent和moduleChild标杆python脚本揭示神秘的时间延迟

我做的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 

所以我的问题是,这些.24多余的秒来自哪里?

感谢您的专业知识。

这里是“childFuntion”的实际代码。它真的不应该需要.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 
+1

这是确切的输出?这些线不正确吗? –

+0

它不是确切的输出,不。这只是一个简单的例子。 –

+0

你有你的答案't2 - t2' = 0 – Lynch

回答

0

编辑2:我只是注意到儿童功能的错字,你有T2 - T2在打印语句

下面忽视:

调用函数本身的开销(设立栈空间,保存局部变量,返回等)。结果表明你的函数是如此微不足道,以至于设置一个函数调用需要比运行代码本身更长的时间。

编辑:另外,调用定时器以及打印广告开销。现在我想起来了,调用print可以占用很多.24秒。 IO很慢。

+0

childFunction是做什么的?很难想象在任何合理的系统上花费0.24秒的函数调用的开销,当然对于可以在0.0秒内完成的函数而言。我想也许你可能会删除最后一个为垃圾收集器释放大量对象的引用。 – RoundTower

+0

更不用说打印时间花费了多少时间,这不包括在它说的时间内。 :-) – MRAB

+0

@MRAB,是的,但打印声明不应该采取.24秒! –

0

您无法通过运行一次来​​测量函数的时间,特别是运行时间过短的时间。有很多因素会影响时间安排,而其中最重要的是您在系统上运行的其他进程。

就像这样我可能会跑至少几百次。查看timeit模块。