[Tutor] Multi threading and I/O bound process
Alan Gauld
alan.gauld at yahoo.co.uk
Mon Nov 29 09:22:27 EST 2021
On 29/11/2021 01:53, Manprit Singh wrote:
> 1) Without multi threading
>
> import time
> import urllib.request
> # a function to dsplay first 25 bytes of a webpage
> def readpage(urladd):
> with urllib.request.urlopen(urladd) as fobj:
> print(fobj.read(25))
>
> t0 = time.time()
Note you start the timer just before the loop after
the intialisation and function definition...
> for _ in range(6):
> readpage("https://www.xyz.com/")
> t1 = time.time()
> print(t1-t0)
> will display the first 25 bytes of the webpage 6 times in a sequential
> order. and measure the time
>
> 2) Multithreading Using constructor :
>
> t0= time.time()
Here you include the thread import and all of the initialisatoion and
class/function definitions that that includes. Not really a fair
comparison, especially on such a small scale example where every mS is
significant.
> import threading
> threadsgrp = []
> for _ in range(6):
> thread = threading.Thread(target=readpage,args=("https://www.xyz.com/
> ",))
> threadsgrp.append(thread)
> thread.start()
> for th in threadsgrp:
> th.join()
> t1 =time.time()
> print(t1-t0)
>
> 3) Multithreading using subclass :
>
> t1 = time.time()
And the same here, you are including the class definition
time in the total. The init/definition code should only
run once in your program so it is not representative of
the time that threading/non-threading takes in a real
work program where threading is called many times in
different places.
> class Techlivethread(threading.Thread):
> def __init__(self, add):
> threading.Thread.__init__(self)
> self.add = add
> def run(self):
> readpage(self.add)
It would be more efficient to transfer the readpage
code into run() directly since all you do is call it.
> grp =[]
> for _ in range(6):
> th1 = Techlivethread("https://www.xyz.com/")
> grp.append(th1)
> th1.start()
> for ele in grp:
> ele.join()
> t2 = time.time()
> print(t2-t1)
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list