this_is_a_float = 2.4
print('Data type: ', type(this_is_a_float))
Data type: <class 'float'>
%load_ext Cython
%%cython
cdef float this_is_a_float = 2.4
print('Data type: ', type(this_is_a_float))
Data type: <class 'float'>
import time
start_time = time.time()
def f(x):
return x**2-x
def integrate_f(a, b, N):
s = 0
dx = (b-a)/N
for i in range(N):
s += f(a+i*dx)
return s * dx
for x in range(0,100): integrate_f(x, 100-x,100)
end_time = time.time()
print(f'{end_time - start_time} seconds')
0.003736734390258789 seconds
%%cython
import time
start_time = time.time()
cdef double f(double x):
return x**2-x
def integrate_f(double a, double b, int N):
cdef int i
cdef double s, x, dx
s = 0
dx = (b-a)/N
for i in range(N):
s += f(a+i*dx)
return s * dx
for x in range(0,100): integrate_f(x, 100-x,100)
end_time = time.time()
print(f'{end_time - start_time} seconds')
5.1021575927734375e-05 seconds
# Bubble sort in python
import numpy as np
def bubbleSort(arr):
for i in range(len(arr)):
for j in range (0, len(arr)-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
np.random.seed(42)
array = list(np.random.randint(0, high=10000, size=10000))
start_time = time.time()
bubbleSort(array)
end_time = time.time()
print(f'Python Bubble Sort sorted 10,000 numbers in {end_time - start_time} seconds')
Python Bubble Sort sorted 10,000 numbers in 13.217506170272827 seconds
%%cython
import time
import numpy as np
# Bubble sort in cython
def bubbleSort(arr):
for i in range(len(arr)):
for j in range (0, len(arr)-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
np.random.seed(42)
array = list(np.random.randint(0, high=10000, size=10000))
start_time = time.time()
bubbleSort(array)
end_time = time.time()
print(f'Cython Bubble Sort sorted 10,000 numbers in {end_time - start_time} seconds')
Cython Bubble Sort sorted 10,000 numbers in 6.08868408203125 seconds
# Factorial in Python
import sys
sys.setrecursionlimit(20000)
def factorial(n):
if n == 0:
return 1 # 0 factorial is just equal to one...
else:
return n * factorial(n-1) # recurse back into our function... an intense task for large computations
start_time = time.time()
ans = factorial(19000)
end_time = time.time()
print(f'Python Factorial X Time: {end_time - start_time} seconds \n19000 factorial has {len(str(ans))} digits')
Python Factorial X Time: 0.13793730735778809 seconds
19000 factorial has 73048 digits
%%cython
import time
import sys
# Factorial in Cython
sys.setrecursionlimit(20000)
def factorial(n):
if n == 0:
return 1 # 0 factorial is just equal to one...
else:
return n * factorial(n-1) # recurse back into our function... an intense task for large computations
start_time = time.time()
ans = factorial(19000)
end_time = time.time()
print(f'Python Factorial X Time: {end_time - start_time} seconds \n19000 factorial has {len(str(ans))} digits')
Python Factorial X Time: 0.0682840347290039 seconds
19000 factorial has 73048 digits