Skip to content

Instantly share code, notes, and snippets.

@subsid
Last active November 4, 2022 14:49
Show Gist options
  • Save subsid/2c6df648a7da76dcc080047423b00ea8 to your computer and use it in GitHub Desktop.
Save subsid/2c6df648a7da76dcc080047423b00ea8 to your computer and use it in GitHub Desktop.
Python ctypes FFI
import ctypes
import threading
import time
def py_loop(i, j):
s = 0
for i in range(i, j):
if (i % 3 == 0):
s += 1
return s
# Compile library
# gcc -fPIC -shared -o clibrary.so clibrary.c
clibrary = ctypes.CDLL("./clibrary.so")
# clibrary.display(b"Sid", 18)
# func = clibrary.display
"""
File clibrary.c
#include <stdio.h>
char* display(char* str, int age) {
printf("My Name is %s and my Age is %d\n", str, age);
return "Completed";
}
int loop(int from, int to)
{
int i;
int s = 0;
for (i = from; i < to; i++)
if (i % 3 == 0)
s += i;
return s;
}
"""
# func.argtypes = [ctypes.c_char_p, ctypes.c_int]
# func.restype = ctypes.c_char_p
# func(b"Sid", 18)
c_loop = clibrary.loop
c_loop.argtypes = [ctypes.c_int, ctypes.c_int]
c_loop.restype = ctypes.c_int
end = 1 * 10**9
fmt = lambda t: f"{t:.2f}"
tic = time.perf_counter()
py_loop(0, end)
py_loop(0, end)
py_loop(0, end)
py_loop(0, end)
print(f"Sequential runtime py_loop {fmt(time.perf_counter() - tic)} Seconds")
tic = time.perf_counter()
t1 = threading.Thread(target=py_loop, args=[0, end])
t2 = threading.Thread(target=py_loop, args=[0, end])
t3 = threading.Thread(target=py_loop, args=[0, end])
t4 = threading.Thread(target=py_loop, args=[0, end])
t1.start()
t2.start()
t3.start()
t4.start()
t1.join()
t2.join()
t3.join()
t4.join()
print(f"Parallet runtime py_loop {fmt(time.perf_counter() - tic)} Seconds")
tic = time.perf_counter()
c_loop(0, end)
c_loop(0, end)
c_loop(0, end)
c_loop(0, end)
print(f"Sequential runtime c_loop {fmt(time.perf_counter() - tic)} Seconds")
tic = time.perf_counter()
t1 = threading.Thread(target=c_loop, args=[0, end])
t2 = threading.Thread(target=c_loop, args=[0, end])
t3 = threading.Thread(target=c_loop, args=[0, end])
t4 = threading.Thread(target=c_loop, args=[0, end])
t1.start()
t2.start()
t3.start()
t4.start()
t1.join()
t2.join()
t3.join()
t4.join()
print(f"Parallet runtime c_loop {fmt(time.perf_counter() - tic)} Seconds")
@subsid
Copy link
Author

subsid commented Nov 4, 2022

Answers
Sequential runtime py_loop 207.47 Seconds
Parallet runtime py_loop 191.43 Seconds
Sequential runtime c_loop 6.93 Seconds
Parallet runtime c_loop 1.89 Seconds

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment