Difference between revisions of "CSC352 Scripts to Measure Execution Times"
(Created page with ' Assume that we want to measure the execution time of this program: <source lang="python"> . #! /usr/bin/python # randomTime.py # D. Thiebaut import random import time time.sl…') |
|||
Line 1: | Line 1: | ||
− | |||
Assume that we want to measure the execution time of this program: | Assume that we want to measure the execution time of this program: | ||
Line 28: | Line 27: | ||
from subprocess import Popen, PIPE | from subprocess import Popen, PIPE | ||
− | def runCommandOnce(): | + | def runCommandOnce( program ): |
− | + | command="(time ./%s) 2>&1 | grep real | cut -d'm' -f 2 | cut -d's' -f 1" % program | |
− | command="(time ./ | ||
p = Popen( command, shell=True, stdin=PIPE, | p = Popen( command, shell=True, stdin=PIPE, | ||
stdout=PIPE, close_fds=True ) | stdout=PIPE, close_fds=True ) | ||
Line 38: | Line 36: | ||
def main(): | def main(): | ||
− | |||
bestTime = 1E10 | bestTime = 1E10 | ||
− | for i in range( | + | program = "randomTime.py" |
− | execTime = runCommandOnce() | + | for i in range( 3 ): |
+ | execTime = runCommandOnce( program ) | ||
print "sample %d: %f sec" % ( i+1, execTime ) | print "sample %d: %f sec" % ( i+1, execTime ) | ||
bestTime = min( bestTime, execTime ) | bestTime = min( bestTime, execTime ) | ||
print "Best time = %f sec" % bestTime | print "Best time = %f sec" % bestTime | ||
+ | |||
Revision as of 11:44, 12 February 2010
Assume that we want to measure the execution time of this program:
.
#! /usr/bin/python
# randomTime.py
# D. Thiebaut
import random
import time
time.sleep( random.randrange( 2 ) )
.
which takes a random number of time between 0 and 2 seconds.
We use a Python script below that will run the program randomTime.py above the right number of times and keep track of the best time.
.
#! /usr/bin/python
# timeIt.py
# D. Thiebaut
from subprocess import Popen, PIPE
def runCommandOnce( program ):
command="(time ./%s) 2>&1 | grep real | cut -d'm' -f 2 | cut -d's' -f 1" % program
p = Popen( command, shell=True, stdin=PIPE,
stdout=PIPE, close_fds=True )
fin, fout = p.stdin, p.stdout
execTime = float( fout.readline() )
return execTime
def main():
bestTime = 1E10
program = "randomTime.py"
for i in range( 3 ):
execTime = runCommandOnce( program )
print "sample %d: %f sec" % ( i+1, execTime )
bestTime = min( bestTime, execTime )
print "Best time = %f sec" % bestTime
main()
.