{"id":2198,"date":"2025-09-15T02:49:44","date_gmt":"2025-09-14T23:19:44","guid":{"rendered":"https:\/\/mshaeri.com\/blog\/?p=2198"},"modified":"2026-05-28T18:41:20","modified_gmt":"2026-05-29T04:41:20","slug":"speed-up-python-with-c-functions","status":"publish","type":"post","link":"https:\/\/mshaeri.com\/blog\/speed-up-python-with-c-functions\/","title":{"rendered":"Speed Up Python With C Functions"},"content":{"rendered":"\n<p>Last weekend, I spent some time exploring how to plug C into Python, how it works, and how much it can speed up things. So I wrote a tiny <strong>C library<\/strong>, called it from <strong>Python <\/strong>using <code><strong>ctypes<\/strong><\/code>, and ran some timings against my C <code>sum <\/code>function, Python\u2019s built-in <code>sum<\/code> and NumPy\u2019s <code>sum<\/code>. It\u2019s a small example project, but it taught me a lot about <strong>cross-platform C libraries<\/strong>, <strong>ctypes<\/strong>, and performance quirks.<\/p>\n\n\n\n<p>Here\u2019s how it went.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Writing the C Library<\/h2>\n\n\n\n<p>I started with a simple goal: write a C function that sums two integers and expose it to Python. That was easy:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"cpp\" class=\"language-cpp\">EXPORT int add(int a, int b) {\n    return a + b;\n}<\/code><\/pre>\n\n\n\n<p>Because of how the <strong>Windows compiler and linker<\/strong> handle DLL exports, if we just compile the above code into a <code>.dll<\/code> on Windows, Python can\u2019t find the <code>add<\/code> function. On Linux and macOS, most global functions are automatically added to the shared library\u2019s symbol table, so tools like Python\u2019s <code>ctypes<\/code> can find them without extra steps. Windows, however, takes the opposite approach: by default nothing is placed into the DLL\u2019s export table unless you explicitly mark it (for example with <code>__declspec(dllexport)<\/code> or a <code>.def<\/code> file). In other words, the OS just loads the DLL and looks at the table of exported symbols, but it\u2019s the <strong>compiler\/linker<\/strong> that decide which functions make it into that table in the first place.Moreover, if we compile with C++, we need <code>extern \"C\"<\/code> to prevent name mangling (these little headaches took me an hour). So the final cross-platform \u201csafe\u201d version should look like this:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"cpp\" class=\"language-cpp\">#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#ifdef _WIN32\n#define EXPORT __declspec(dllexport)\n#else\n#define EXPORT\n#endif\n\nEXPORT int add(int a, int b) {\n    return a + b;\n}\n\nEXPORT int sum_array(const int* arr, int size) {\n    int sum = 0;\n    for (int i = 0; i &lt; size; i++) {\n        sum += arr[i];\n    }\n    return sum;\n}\n\n#ifdef __cplusplus\n}\n#endif\n<\/code><\/pre>\n\n\n\n<p>Here, <code>sum_array<\/code> sums a pointer to an array of integers. Notice that I pass the array <strong>as a pointer<\/strong> and explicitly provide its size, that\u2019s the C way.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Compiling C Code<\/h2>\n\n\n\n<p>The next step is compiling it into a <strong>shared library<\/strong> that Python can use. The commands differ slightly depending on your platform:<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">On Windows (with MinGW)<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"bash\" class=\"language-bash\">gcc -shared -o math_lib.dll -fPIC math_lib.c<\/code><\/pre>\n\n\n\n<ul>\n<li><code>-shared<\/code> tells the compiler to make a DLL.<\/li>\n\n\n\n<li><code>-fPIC<\/code> ensures position-independent code, which is required for shared libraries. <\/li>\n<\/ul>\n\n\n\n<p>If you\u2019re using Microsoft\u2019s compiler (<code>cl.exe<\/code>):<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"bash\" class=\"language-bash\">cl \/LD math_lib.c\n<\/code><\/pre>\n\n\n\n<p>This generates <code>math_lib.dll<\/code> along with an import library.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">On Linux\/macOS<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"bash\" class=\"language-bash\">gcc -shared -o math_lib.so -fPIC math_lib.c\n<\/code><\/pre>\n\n\n\n<ul>\n<li><code>.so<\/code> is the shared object file for Unix-like systems.<\/li>\n<\/ul>\n\n\n\n<p>After compiling, the library is ready to be loaded in Python with <code>ctypes<\/code>.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Calling C from Python<\/h2>\n\n\n\n<p>Thanks to <code>ctypes<\/code>, I could easily call C functions in Python:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"python\" class=\"language-python\">import ctypes\nimport os\nimport numpy as np\n\nlibname = os.path.abspath(\"math_lib.dll\") &nbsp;# or \"libadd.so\" on Linux\/mac\nmath_lib = ctypes.CDLL(libname)\n\n# Tell Python about argument types\nmath_lib.sum_array.argtypes = (ctypes.POINTER(ctypes.c_int), ctypes.c_int)\nmath_lib.sum_array.restype = ctypes.c_int\n\narr = np.array([random.randint(0, 100) for _ in range(10_000_000)], dtype=np.int32)\narr_ptr = arr.ctypes.data_as(ctypes.POINTER(ctypes.c_int))\n\ntotal = math_lib.sum_array(arr_ptr, 10_000_000)\nprint(f\"Sum of array: {total}\")<\/code><\/pre>\n\n\n\n<p>Wow! Really fascinating, getting result from C function in Python:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"bash\" class=\"language-bash\">Sum of array: 499959582<\/code><\/pre>\n\n\n\n<p>Notice how we use a <strong>NumPy array<\/strong> and get a pointer to pass to C. This ensures the data is contiguous in memory, crucial for C to process it correctly.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Timing the Sum<\/h2>\n\n\n\n<p>I wanted to see how fast C really is compared to Python\u2019s built-in <code>sum<\/code> and NumPy\u2019s <code>sum<\/code> in array with 10 million items:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"python\" class=\"language-python\">import timeit\nimport array\n\n# Python list sum\npy_time = timeit.timeit(lambda: sum(list(arr)), number=1)\n\n# NumPy sum\nnp_time = timeit.timeit(lambda: np.sum(arr), number=1)\n\n# C function sum\nc_time = timeit.timeit(lambda: math_lib.sum_array(arr_ptr, 10_000_000), number=1)\n\n# Time Python array.array sum\npy_array_time = timeit.timeit(lambda: sum(array.array(\"i\", arr)), number=1)\n<\/code><\/pre>\n\n\n\n<p>And the results were fascinating:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code lang=\"bash\" class=\"language-bash\">NumPy sum of items: 0.004496 sec\nC sum_array of items: 0.034218 sec    \nPython list sum of items: 0.379953 sec\nPython array.array sum of items: 0.113865 sec<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<ul>\n<li><strong>C is faster than Python<\/strong>, as expected. Compiled code running a tight loop in memory beats Python\u2019s interpreted loop.<\/li>\n\n\n\n<li><strong>Python list sum is slow<\/strong>, almost 10x slower than our C function. That\u2019s because Python loops over list elements in the interpreter, one item at a time.<\/li>\n\n\n\n<li><strong>Python array.array<\/strong> is faster than Python list because it stores raw integers in contiguous memory. But slower than C.<\/li>\n\n\n\n<li><strong>NumPy is fastest<\/strong>, not surprisingly, even faster than our C function. Because NumPy is implemented in optimized C internally and often uses vectorized instructions (SIMD) to sum arrays efficiently. Also, <code>numpy.sum<\/code> can process the data in chunks, leveraging CPU caches better than our naive loop.<\/li>\n<\/ul>\n\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Last weekend, I spent some time exploring how to plug C into Python, how it works, and how much it can speed up things. So &hellip; <\/p>\n","protected":false},"author":1,"featured_media":2216,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[200,1,35,41],"tags":[319,316,8,315,318,317,39],"_links":{"self":[{"href":"https:\/\/mshaeri.com\/blog\/wp-json\/wp\/v2\/posts\/2198"}],"collection":[{"href":"https:\/\/mshaeri.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/mshaeri.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/mshaeri.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/mshaeri.com\/blog\/wp-json\/wp\/v2\/comments?post=2198"}],"version-history":[{"count":5,"href":"https:\/\/mshaeri.com\/blog\/wp-json\/wp\/v2\/posts\/2198\/revisions"}],"predecessor-version":[{"id":2488,"href":"https:\/\/mshaeri.com\/blog\/wp-json\/wp\/v2\/posts\/2198\/revisions\/2488"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/mshaeri.com\/blog\/wp-json\/wp\/v2\/media\/2216"}],"wp:attachment":[{"href":"https:\/\/mshaeri.com\/blog\/wp-json\/wp\/v2\/media?parent=2198"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/mshaeri.com\/blog\/wp-json\/wp\/v2\/categories?post=2198"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/mshaeri.com\/blog\/wp-json\/wp\/v2\/tags?post=2198"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}