Skip to content

Instantly share code, notes, and snippets.

@lbolla
Last active January 1, 2016 05:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save lbolla/8098030 to your computer and use it in GitHub Desktop.
Save lbolla/8098030 to your computer and use it in GitHub Desktop.
Python GIL and Cython
from threading import Thread
def busy_sleep(n):
while n > 0:
n -= 1
N = 99999999
t1 = Thread(target=busy_sleep, args=(N, ))
t2 = Thread(target=busy_sleep, args=(N, ))
t1.start()
t2.start()
t1.join()
t2.join()
def busy_sleep(int n):
_busy_sleep(n)
def busy_sleep_nogil(int n):
with nogil:
_busy_sleep(n)
cdef inline void _busy_sleep(int n) nogil:
cdef double tmp = 0.0
while n > 0:
# Do some CPU intensive useless computation to waste some time
tmp = (n ** 0.5) ** 0.5
n -= 1
def busy_sleep(n):
while n > 0:
n -= 1
N = 99999999
busy_sleep(N)
busy_sleep(N)
import pyximport
pyximport.install()
import time
from threading import Thread
import parpyx
N = 39999999
t0 = time.time()
parpyx.busy_sleep(N)
parpyx.busy_sleep(N)
print 'SEQ Elapsed: %.4f' % (time.time() - t0)
t0 = time.time()
t1 = Thread(target=parpyx.busy_sleep_nogil, args=(N, ))
t2 = Thread(target=parpyx.busy_sleep_nogil, args=(N, ))
t1.start()
t2.start()
t1.join()
t2.join()
print 'PAR Elapsed: %.4f' % (time.time() - t0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment