November 18, 2026
python c_type c

Speed Up Python With C Functions

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 C library, called it from Python using ctypes, and ran some timings against my C sum function, Python’s built-in sum and NumPy’s sum. It’s a small example project, but it taught me a lot about cross-platform C libraries, ctypes, and performance quirks.

Here’s how it went.

Writing the C Library

I started with a simple goal: write a C function that sums two integers and expose it to Python. That was easy:

EXPORT int add(int a, int b) {
    return a + b;
}

Because of how the Windows compiler and linker handle DLL exports, if we just compile the above code into a .dll on Windows, Python can’t find the add function. On Linux and macOS, most global functions are automatically added to the shared library’s symbol table, so tools like Python’s ctypes can find them without extra steps. Windows, however, takes the opposite approach: by default nothing is placed into the DLL’s export table unless you explicitly mark it (for example with __declspec(dllexport) or a .def file). In other words, the OS just loads the DLL and looks at the table of exported symbols, but it’s the compiler/linker that decide which functions make it into that table in the first place.Moreover, if we compile with C++, we need extern "C" to prevent name mangling (these little headaches took me an hour). So the final cross-platform “safe” version should look like this:

#ifdef __cplusplus
extern "C" {
#endif

#ifdef _WIN32
#define EXPORT __declspec(dllexport)
#else
#define EXPORT
#endif

EXPORT int add(int a, int b) {
    return a + b;
}

EXPORT int sum_array(const int* arr, int size) {
    int sum = 0;
    for (int i = 0; i < size; i++) {
        sum += arr[i];
    }
    return sum;
}

#ifdef __cplusplus
}
#endif

Here, sum_array sums a pointer to an array of integers. Notice that I pass the array as a pointer and explicitly provide its size, that’s the C way.


Compiling C Code

The next step is compiling it into a shared library that Python can use. The commands differ slightly depending on your platform:

On Windows (with MinGW)

gcc -shared -o math_lib.dll -fPIC math_lib.c
  • -shared tells the compiler to make a DLL.
  • -fPIC ensures position-independent code, which is required for shared libraries.

If you’re using Microsoft’s compiler (cl.exe):

cl /LD math_lib.c

This generates math_lib.dll along with an import library.

On Linux/macOS

gcc -shared -o math_lib.so -fPIC math_lib.c
  • .so is the shared object file for Unix-like systems.

After compiling, the library is ready to be loaded in Python with ctypes.


Calling C from Python

Thanks to ctypes, I could easily call C functions in Python:

import ctypes
import os
import numpy as np

libname = os.path.abspath("math_lib.dll")  # or "libadd.so" on Linux/mac
math_lib = ctypes.CDLL(libname)

# Tell Python about argument types
math_lib.sum_array.argtypes = (ctypes.POINTER(ctypes.c_int), ctypes.c_int)
math_lib.sum_array.restype = ctypes.c_int

arr = np.array([random.randint(0, 100) for _ in range(10_000_000)], dtype=np.int32)
arr_ptr = arr.ctypes.data_as(ctypes.POINTER(ctypes.c_int))

total = math_lib.sum_array(arr_ptr, 10_000_000)
print(f"Sum of array: {total}")

Wow! Really fascinating, getting result from C function in Python:

Sum of array: 499959582

Notice how we use a NumPy array and get a pointer to pass to C. This ensures the data is contiguous in memory, crucial for C to process it correctly.


Timing the Sum

I wanted to see how fast C really is compared to Python’s built-in sum and NumPy’s sum in array with 10 million items:

import timeit
import array

# Python list sum
py_time = timeit.timeit(lambda: sum(list(arr)), number=1)

# NumPy sum
np_time = timeit.timeit(lambda: np.sum(arr), number=1)

# C function sum
c_time = timeit.timeit(lambda: math_lib.sum_array(arr_ptr, 10_000_000), number=1)

# Time Python array.array sum
py_array_time = timeit.timeit(lambda: sum(array.array("i", arr)), number=1)

And the results were fascinating:

NumPy sum of items: 0.004496 sec
C sum_array of items: 0.034218 sec    
Python list sum of items: 0.379953 sec
Python array.array sum of items: 0.113865 sec

  • C is faster than Python, as expected. Compiled code running a tight loop in memory beats Python’s interpreted loop.
  • Python list sum is slow, almost 10x slower than our C function. That’s because Python loops over list elements in the interpreter, one item at a time.
  • Python array.array is faster than Python list because it stores raw integers in contiguous memory. But slower than C.
  • NumPy is fastest, 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, numpy.sum can process the data in chunks, leveraging CPU caches better than our naive loop.

Leave a Reply

Your email address will not be published. Required fields are marked *