Python 对子流程完成所需的时间进行计时

Python 对子流程完成所需的时间进行计时,python,python-2.7,subprocess,Python,Python 2.7,Subprocess,我目前有一个方法,可以通过使用子进程调用来执行其他python脚本,我想知道是否还有其他方法可以计算完成这个过程需要多长时间?脚本是在一个时间间隔内运行的,我想从中获得的是检查脚本是否在该时间间隔内完成 def execute_scripts(script_name): process = sp.Popen(['python2.7', script_name]) print 'executing - ' + script_name 在脚本执行时,是否需要程序保持运行?如果没有,

我目前有一个方法,可以通过使用子进程调用来执行其他python脚本,我想知道是否还有其他方法可以计算完成这个过程需要多长时间?脚本是在一个时间间隔内运行的,我想从中获得的是检查脚本是否在该时间间隔内完成

def execute_scripts(script_name):
    process = sp.Popen(['python2.7', script_name])
    print 'executing - ' + script_name

在脚本执行时,是否需要程序保持运行?如果没有,您可以阻止程序执行,直到进程完成,并报告所用的时间:

def execute_scripts(script_name):
    time_start = time.time()
    print "starting process"
    process = sp.call(['python2.7', script_name])
    print 'finished process %s in %s s" % (process, time.time() - start_time)
用于计时少量代码的执行

#sleep2.py
import time
time.sleep(2)
您需要使用来阻止,直到调用完成

import timeit
import subprocess as sp

def execute_scripts(script_name):
    process = sp.call(['python2.7', script_name])
    print 'executing - ' + script_name

t = timeit.Timer("execute_scripts('sleep2.py')", setup="from __main__ import execute_scripts")


print 'time taken : %f seconds' % t.timeit(1)


executing - sleep2.py
time taken : 2.032273 seconds
或者,您可以通过编写一个decorator来计时任何函数调用来概括这一点

import time
import  subprocess as sp

def timed_execution(function):
    def wrapper(arg):
        t1 = time.time()
        function(arg)
        t2 = time.time()
        return 'time taken : %f seconds' % (t2 - t1) + "\n"
   return wrapper


@timed_execution
def execute_scripts(script_name):
    sp.call(['python2.7', script_name])
    print 'executing - ' + script_name


print execute_scripts('sleep2.py')

executing - sleep2.py
time taken : 2.025291 seconds

相关:@DorkMonstuh这些答案中有没有可以接受的?嗨,这似乎是一个阻塞调用,是否可能有非阻塞以及脚本运行所需的时间?@DorkMonstuh:是的。最简单的方法(代码方面)是将
process.wait()
调用放入后台线程,以避免阻塞主线程。或者您可以存储开始时间和(后一种方法的级别可能太低)。