Measuring time needed to recieve content of given URI(s) with Python
December 26th, 2007
My hosting was damn slow today so I decided to yell at some poor guys out there to get some speed. It’s allways better to have some arguments on you so I thought that showing some numbers would be fine. To demonstrate how slow my domain is I decided to compare the time needed to obtain my page with time needed for getting page from Seznam.cz. You are probably starting to laugh at me just now. Why should I do this for? It’s comparing like comparing elephant’s poo with safe water. No match? Correct :> I will share the code nevertheless just for fun. So let’s get started, shall we?
We need a simple function which handles the HTTP request:
import urllib2
try:
f = urllib2.urlopen(url)
except urllib2.HTTPError, e:
print e.code
sys.exit()
except urllib2.URLError, e:
print e.reason
sys.exit()
And now we just loop thru URIs within argv and run the Timer.repeat() method on each one. Note that we have to import the fetch_page function in setup argument in order to use it further in the stmt. The repeat method calls timeit method with number of iterations specified as it’s second argument and repeats this first_argument*times. The minimum value of all measured is printed out.
import sys
if len(sys.argv)>2:
from timeit import Timer
for a in range(1,len(sys.argv)):
print sys.argv[a]
print ‘- min: ‘+str(min(Timer(setup="from __main__ import fetch_page", \ stmt="fetch_page(%s)"%(‘"’+sys.argv[a]+‘"’)).repeat(3,3)))+’s\n‘
else: print ‘\nERR:lack of parameters\nusage:\n‘+sys.argv[0]+\
‘ http://www.first.uri [http://www.second.one] …. [www.n-th.uri]’
Popularity: 13% [?]
