Execution time of multithreaded python program
Question: Considering GIL, I expected this program to finish in 9 seconds, but to my
surprise, it ends in 4 seconds. Looking for probable reasons or am I missing
something?

    
    
    import time
    import threading
    
    def get_data(start, end):
        res = []
        for i in range(start, end):
            time.sleep(1)
            res.append(i)
        print res
    
    
    range_list = [(1,4), (4,7), (6,10)]
    for r in range_list:
        t = threading.Thread(target=get_data, args = (r[0], r[1]))
        t.start()
    

Time of execution:-

Without threading - 9sec

With threading - 4 sec


Answer: Normally, if you don't use multithreading this program finish in 9 seconds
because python runs lines one by one so when you put time.sleep(1), python
just wait one second and on the other hand do not anything. But when you use
multithreading the program runs thread functions separately. So for example if
you call thread function 2 times, the thread function runs line by line
seperately in the same time.

In this program, you call thread function for 3 times. First call, python wait
3 seconds for i =1,i=2,i=3 and second call, python wait 3 seconds for i
=4,i=5,i=6 and final call python wait 4 seconds for i =6,i=7,i=8,i=9. This
codes runs separately each other so this program finish in 4 second because
the biggest time is 4 seconds.

