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

From dftwiki3
Jump to: navigation, search
Line 27: Line 27:
 
from subprocess import Popen, PIPE
 
from subprocess import Popen, PIPE
  
def runCommandOnce( program ):
+
def oldRunCommandOnce( program ):
 
   command="(time  ./%s) 2>&1 | grep real | cut -d'm' -f 2 | cut -d's' -f 1" % 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,  
 
   p = Popen( command, shell=True, stdin=PIPE,  
Line 34: Line 34:
 
   execTime = float( fout.readline() )
 
   execTime = float( fout.readline() )
 
   return execTime
 
   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():
 
def main():

Revision as of 15:55, 21 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 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()


.