CSC352 Scripts to Measure Execution Times

From dftwiki3
Revision as of 15:55, 21 February 2010 by Thiebaut (talk | contribs)
Jump to: navigation, search

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 oldRunCommandOnce( 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 runCommandOnce( program ):
  command="(/usr/bin/time  ./%s) 2>&1 | grep real" % program
  p = Popen( command, shell=True, stdin=PIPE,
                        stdout=PIPE, close_fds=True )
  fin, fout = p.stdin, p.stdout
  line = fout.readline()
  #print	"line =	", line
  words = line.split()
  execTime = float( words[0] )
  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()


.