5 November 2007

Average site performance tester

Today I was doing some performance tests connected to dynamic site generation. As a result I created small script in Python that helps me doing those tests. Because the code is very simple (for example no exception handling) and is one of my first tools in Python, I want to share it.

from timeit import Timer
import urllib2
import random
import sys

REPETITIONS = 1000
REFERERS_LIST = ('http://www.example.com/1.html',
'http://www.example.com/2.html')
STD_URLS = ('http://www.example.com/3.html',
'www.example.com/4.html')

def get_ad(url_pool, referer_pool = REFERERS_LIST):
"""Read and forget several bytes from one of url_pool URLs using one of referer_pool URLs as Referer."""
url = random.choice(url_pool)
referer = random.choice(referer_pool)
req = urllib2.Request(url)
req.add_header('Referer', referer)
#Open url and read at least several bytes
urlfile = urllib2.urlopen(req)
urlfile.read(16)
urlfile.close()

def run_tests(pools):
"""Run performance test for URLs from pools list."""
for pool in pools:
print 'Running test for %s...' % (pool,)
list = getattr(sys.modules[__name__], pool)
t = Timer("get_ad(%s)" % pool, "from %s import get_ad, %s" % (__name__, pool))
print "%.3f msec/url" % (1000 * t.timeit(REPETITIONS)/REPETITIONS)

if __name__ == '__main__':
run_tests(('STD_URLS',))

You can define as many _URLS tuples or lists as you wish. Code will test them all using randomly selected URL for every simple connection. Then just add names of those lists to run_tests() call. Thats all folks!

0 komentarze:

Post a Comment