[Tutor] threads

John Moylan johnm at rte.ie
Mon Dec 1 12:17:51 EST 2003


I found the following somewhere on the web a while back. 
I don't know who to attribute it too, but it is the best
starting point I found for programming threads in Python.
here goes:


#!/usr/bin/env python
import urllib, time
import threading

retrieveDoc = 1
numPings = 20
numThreads = 5

url = 'http://localhost/'



class ping ( threading.Thread ) :
    def __init__ ( self, url, numPings, retrieveDoc=1 ) :
        self.url = url
        self.numPings = numPings
        self.retrieveDoc = retrieveDoc
        threading.Thread.__init__(self)

    def run ( self ) :
        StartTime = time.time()
        for i in range(self.numPings):
            page = urllib.urlopen ( self.url )
            if self.retrieveDoc:
                page.read()
            page.close()
        EndTime = time.time()
        self.TotalTime = EndTime - StartTime



if __name__ == '__main__' :
    threadList = []
    for i in range(numThreads) :
        thread = ping( url, numPings, retrieveDoc )
        threadList.append ( thread )

    StartTime = time.time()
    for thread in threadList :
        thread.start()

    while threading.activeCount() > 1 :
        print ".",
        time.sleep(1)
    EndTime = time.time()
    TotalTime = EndTime - StartTime
    print

    TotalPings = 0
    ThreadTime = 0
    for thread in threadList :
        TotalPings = TotalPings + thread.numPings
        ThreadTime = ThreadTime + thread.TotalTime

    PingAvg = TotalPings / TotalTime
    ResponseAvg = ThreadTime / TotalPings

    print "Threads: ", numThreads
    print "Pings:", TotalPings
    print "Total time:", TotalTime
    print "Pings per second:", PingAvg
    print "Average response time (secs):", ResponseAvg



******************************************************************************
The information in this e-mail is confidential and may be legally privileged.
It is intended solely for the addressee. Access to this e-mail by anyone else
is unauthorised. If you are not the intended recipient, any disclosure,
copying, distribution, or any action taken or omitted to be taken in reliance
on it, is prohibited and may be unlawful.
Please note that emails to, from and within RTÉ may be subject to the Freedom
of Information Act 1997 and may be liable to disclosure.
******************************************************************************



More information about the Tutor mailing list