我目前有一种方法,通过使用子进程调用执行其他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
#sleep2.py
import time
time.sleep(2)
您需要使用subprocess.call来阻塞程序直到调用完成。
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
或者,您可以编写一个装饰器来计时任何函数调用。
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
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)
process.wait()
调用放入后台线程中,以避免阻塞主线程。或者您可以存储开始时间并定义SIGCHILD
信号处理程序来查找结束时间。(后一种方法可能过于低级)。 - jfs