atime

Quite a few times now I had to time a program and take the average execution time. I normally did this with a little bash loop and then used a rough estimate or gnuplot to tell me the average runtime. Now I wrote a little python script that does exactly that. So you give it a number of loops and the program to execute.
$  ./atime.py 4 "sleep 0.5"
real 0.5
user 0.0
sys 0.0

for now you have to put the commands in quotes so it will pass in the whole command. Further be carefull not to loop to many times. Error catching works on a very rudenmental level.
$  ./atime.py 4 "xyz"
A error in the command has happend
/bin/sh: xyz: command not found

So if for your next assignment you need to take the average value of a program run time try atime.


 1 #!/usr/bin/python
2 # A little tool that takes in a count and a command to
3 # run and averages the execution time
4 # ribalba@gmail.com
5
6 import sys;
7 import string;
8 import os;
9
10 av_real = av_user = av_sys= 0
11
12 looptimes = string.atoi(sys.argv[1])
13
14 for i in xrange(looptimes):
15 commandout = os.popen3("time -p " + sys.argv[2])
16 sys.stdout.write ( commandout[1].read(),);
17 steddout = commandout[2].readlines()
18 if (len (steddout) > 3):
19 sys.stderr.write("A error in the command has happend\n")
20 sys.stderr.write(steddout[0] + "\n")
21 sys.exit()
22 av_real += (string.atof(steddout[0].split()[1]) / looptimes)
23 av_user += (string.atof(steddout[1].split()[1]) / looptimes)
24 av_sys += (string.atof(steddout[2].split()[1]) / looptimes)
25 else:
26 sys.stderr.write("real " + str(av_real) + "\n")
27 sys.stderr.write("user " + str(av_user) + "\n")
28 sys.stderr.write("sys " + str(av_sys ) + "\n")

[DOWNLOAD]

No comments: