I currently have a method that executes other python scripts by using subprocess calls, I was wondering if there was anyway I could time how long it takes for this to complete? The scripts are running in an interval, what I want to achieve from this is to check whether the scripts finish within that interval.
def execute_scripts(script_name):
process = sp.Popen(['python2.7', script_name])
print 'executing - ' + script_name
Use timeit to time the execution of small bits of code.
#sleep2.py
import time
time.sleep(2)
You need to use subprocess.call to block until the call is finished.
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
Alternatively, you can generalise this by writing a decorator to time any function call
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With