【问题标题】:Timing how long it takes for subprocess to complete计时完成子流程需要多长时间
【发布时间】:2016-09-23 03:35:17
【问题描述】:

我目前有一个通过使用子进程调用执行其他 python 脚本的方法,我想知道是否无论如何我可以计算完成这需要多长时间?脚本在一个间隔内运行,我想要实现的是检查脚本是否在该间隔内完成。

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

【问题讨论】:

标签: python python-2.7 subprocess


【解决方案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

【讨论】:

    【解决方案2】:

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

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-23
      • 2022-07-18
      • 1970-01-01
      • 2011-03-30
      相关资源
      最近更新 更多