Skip to content

Instantly share code, notes, and snippets.

@dev-tim
Created July 5, 2023 11:30
Show Gist options
  • Save dev-tim/9748e8c8ff5161844e9947b83effcad9 to your computer and use it in GitHub Desktop.
Save dev-tim/9748e8c8ff5161844e9947b83effcad9 to your computer and use it in GitHub Desktop.
Python GIL impact

GIL https://wiki.python.org/moin/GlobalInterpreterLock

Benchmark

5 threads:

python3 ./multithreading.py                               
Execution time with GIL:  20.465982913970947
Execution time without GIL:  4.411532878875732

10 threads:

python3 ./multithreading.py                               
Execution time with GIL:  43.809110164642334
Execution time without GIL:  6.819617748260498
import time
import threading
NUM_PROCESSES = 10
NUM_THREADS = 10
def count_down(n):
while n > 0:
n -= 1
def run_test():
threads = []
for i in range(NUM_THREADS):
# Create two threads to execute the count_down function
threads.append(threading.Thread(target=count_down, args=(100000000,)))
# Start the threads
threads[i].start()
for i in range(NUM_THREADS):
# Wait for both threads to finish
threads[i].join()
if __name__ == '__main__':
# Measure the execution time with the GIL
start_time = time.time()
run_test()
end_time = time.time()
execution_time_with_gil = end_time - start_time
print("Execution time with GIL: ", execution_time_with_gil)
# Measure the execution time without the GIL using multiprocessing
import multiprocessing
multiprocessing.freeze_support()
start_time = time.time()
processes = []
for i in range(NUM_PROCESSES):
# Create two threads to execute the count_down function
processes.append(multiprocessing.Process(target=count_down, args=(100000000,)))
# Start the threads
processes[i].start()
for i in range(NUM_PROCESSES):
# Wait for both threads to finish
processes[i].join()
end_time = time.time()
execution_time_without_gil = end_time - start_time
print("Execution time without GIL: ", execution_time_without_gil)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment