计时子流程完成需要多长时间
Timing how long it takes for subprocess to complete
我目前有一个方法可以通过使用子进程调用来执行其他 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)
使用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
我目前有一个方法可以通过使用子进程调用来执行其他 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)
使用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