Difference between revisions of "CSC352 Scripts to Measure Execution Times"

From dftwiki3
Jump to: navigation, search
(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 ):
  """run the randomTime.py program once and returns its execution time"""
+
   command="(time  ./%s) 2>&1 | grep real | cut -d'm' -f 2 | cut -d's' -f 1" % program
   command="(time  ./randomTime.py) 2>&1 | grep real | cut -d'm' -f 2 | cut -d's' -f 1"
 
 
   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():
  """calls runCommandOnce 4 times and keep track of the best execution time"""
 
 
   bestTime = 1E10
 
   bestTime = 1E10
   for i in range( 4 ):
+
  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()


.