A Python program to make use of the module is very similar to the previous program:
import Pi
import time
if __name__ == '__main__':
N=10000000
t1=time.perf_counter()
pi=Pi.myPi(1,N)
t2=time.perf_counter()
print((t2-t1)*1000)
print(pi)
So how much faster is the C extension than the pure Python?
The first thing to say is that this extension should exhibit the maximum speed gain. The pure Python program delegates nothing to any existing C modules and the C extension interacts minimally with Python. The only time lost is initializing the module and making the single call to the function. On a middle-of-the range PC the pure Python program takes 2.5 seconds and the extension takes 50ms, a speedup of 50 times. On a Raspberry Pi 4 the pure Python program takes 3.2 seconds and the extension takes 89ms, a speedup of 35 times.
Of course, the speedup you see from using an extension is unlikely to be this great as the task becomes more complex and requires more processing to interface the C and Python code, but it should still be worth the effort.
In chapter but not in this extract
Example Module
Summary
The main principle of the C API is that all Python objects are represented by a specific C Struct that is an extension of PyObject and as a result any Python object can be referenced by a PyObject*
The C API contains many of the functions that implement Python. In many cases there is a simple equivalence between Python functions and C functions.
Every module has an initialization function with the name PyInit_modulename.
The initialization function is called when the module is imported and it creates the module object and returns it.
The PyModuleDef struct has fields that determine how the module will be treated by the system.
An array of PyMethodDef structs specifies the methods/functions that the module provides.
The PyArg_ParseTuple function can be used to parse the tuple of arguments passed to the function.
A simple calculation demonstrates that converting a Python function to C can speed it up by a factor of roughly 50.
To avoid having to change the compiler settings, a standard example extension is used in the rest of this book.
Google is offering a 5-Day Gen AI Intensive Course designed to equip data scientists with the knowledge and skills to tackle generative AI projects with confidence. It runs on the Kaggle platform from [ ... ]
pg_parquet is a new extension by Crunchy Data that allows a PostgreSQL instance to work with Parquet files. With pg_duckdb, pg_analytics and pg_mooncake all of which can access Parquet files, is [ ... ]