CSC352 Scripts to Measure Execution Times

From dftwiki3
Revision as of 17:15, 11 February 2010 by Thiebaut (talk | contribs) (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…')
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
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 runCommandOnce():
  """run the randomTime.py program once and returns its execution time"""
  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, 
                        stdout=PIPE, close_fds=True )
  fin, fout = p.stdin, p.stdout
  execTime = float( fout.readline() )
  return execTime

def main():
  """calls runCommandOnce 4 times and keep track of the best execution time"""
  bestTime = 1E10
  for i in range( 4 ):
    execTime = runCommandOnce()
    print "sample %d: %f sec" % ( i+1, execTime )
    bestTime = min( bestTime, execTime )

  print "Best time = %f sec" % bestTime


main()


.