我目前有一个通过使用子进程调用执行其他python脚本的方法,我想知道是否有时间我可以计算完成它需要多长时间?脚本在一个时间间隔内运行,我想要实现的是检查脚本是否在该时间间隔内完成。
def execute_scripts(script_name):
process = sp.Popen(['python2.7', script_name])
print 'executing - ' + script_name
答案 0 :(得分:1)
使用timeit计算少量代码的执行时间。
#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
答案 1 :(得分:0)
您是否需要程序在脚本执行时继续运行?如果没有,您可以阻止程序执行,直到流程完成并报告花费的时间:
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)