10000 Initial checkin · CodeByAidan/Cython-Tutorial@13f8966 · GitHub
[go: up one dir, main page]

Skip to content

Commit 13f8966

Browse files
committed
Initial checkin
1 parent a3f1162 commit 13f8966

File tree

7 files changed

+340
-0
lines changed

7 files changed

+340
-0
lines changed

.gitignore

Lines changed: 161 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,161 @@
1+
# Byte-compiled / optimized / DLL files
2+
__pycache__/
3+
*.py[cod]
10000 4+
*$py.class
5+
6+
# C extensions
7+
*.so
8+
9+
# Distribution / packaging
10+
.Python
11+
build/
12+
my_module.c
13+
develop-eggs/
14+
dist/
15+
downloads/
16+
eggs/
17+
.eggs/
18+
lib/
19+
lib64/
20+
parts/
21+
sdist/
22+
var/
23+
wheels/
24+
share/python-wheels/
25+
*.egg-info/
26+
.installed.cfg
27+
*.egg
28+
MANIFEST
29+
30+
# PyInstaller
31+
# Usually these files are written by a python script from a template
32+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
33+
*.manifest
34+
*.spec
35+
36+
# Installer logs
37+
pip-log.txt
38+
pip-delete-this-directory.txt
39+
40+
# Unit test / coverage reports
41+
htmlcov/
42+
.tox/
43+
.nox/
44+
.coverage
45+
.coverage.*
46+
.cache
47+
nosetests.xml
48+
coverage.xml
49+
*.cover
50+
*.py,cover
51+
.hypothesis/
52+
.pytest_cache/
53+
cover/
54+
55+
# Translations
56+
*.mo
57+
*.pot
58+
59+
# Django stuff:
60+
*.log
61+
local_settings.py
62+
db.sqlite3
63+
db.sqlite3-journal
64+
65+
# Flask stuff:
66+
instance/
67+
.webassets-cache
68+
69+
# Scrapy stuff:
70+
.scrapy
71+
72+
# Sphinx documentation
73+
docs/_build/
74+
75+
# PyBuilder
76+
.pybuilder/
77+
target/
78+
79+
# Jupyter Notebook
80+
.ipynb_checkpoints
81+
82+
# IPython
83+
profile_default/
84+
ipython_config.py
85+
86+
# pyenv
87+
# For a library or package, you might want to ignore these files since the code is
88+
# intended to run in multiple environments; otherwise, check them in:
89+
# .python-version
90+
91+
# pipenv
92+
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
93+
# However, in case of collaboration, if having platform-specific dependencies or dependencies
94+
# having no cross-platform support, pipenv may install dependencies that don't work, or not
95+
# install all needed dependencies.
96+
#Pipfile.lock
97+
98+
# poetry
99+
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
100+
# This is especially recommended for binary packages to ensure reproducibility, and is more
101+
# commonly ignored for libraries.
102+
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
103+
#poetry.lock
104+
105+
# pdm
106+
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
107+
#pdm.lock
108+
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
109+
# in version control.
110+
# https://pdm.fming.dev/#use-with-ide
111+
.pdm.toml
112+
113+
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
114+
__pypackages__/
115+
116+
# Celery stuff
117+
celerybeat-schedule
118+
celerybeat.pid
119+
120+
# SageMath parsed files
121+
*.sage.py
122+
123+
# Environments
124+
.env
125+
.venv
126+
env/
127+
venv/
128+
ENV/
129+
env.bak/
130+
venv.bak/
131+
132+
# Spyder project settings
133+
.spyderproject
134+
.spyproject
135+
136+
# Rope project settings
137+
.ropeproject
138+
139+
# mkdocs documentation
140+
/site
141+
142+
# mypy
143+
.mypy_cache/
144+
.dmypy.json
145+
dmypy.json
146+
147+
# Pyre type checker
148+
.pyre/
149+
150+
# pytype static type analyzer
151+
.pytype/
152+
153+
# Cython debug symbols
154+
cython_debug/
155+
156+
# PyCharm
157+
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
158+
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
159+
# and can be added to the global gitignore or merged into this file. For a more nuclear
160+
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
161+
.idea/

README.rst

Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
.. image:: https://cdn.discordapp.com/emojis/1140027508427857960.webp?size=80&quality=lossless
2+
:target: https://cdn.discordapp.com/emojis/1140027508427857960.webp?size=80&quality=lossless
3+
4+
Cython Tutorial: Boosting Python Performance with C
5+
===================================================
6+
.. image:: https://img.shields.io/pypi/v/cython.svg
7+
:target: https://pypi.python.org/pypi/cython
8+
.. image:: https://img.shields.io/pypi/pyversions/cython.svg
9+
:target: https://pypi.python.org/pypi/cython
10+
.. image:: https://img.shields.io/pypi/l/cython.svg
11+
:target: https://pypi.python.org/pypi/cython
12+
.. image:: https://img.shields.io/pypi/dm/cython.svg
13+
:target: https://pypi.python.org/pypi/cython
14+
15+
Introduction
16+
------------
17+
18+
Welcome to the Cython Tutorial! If you're new to the world of Python or even if you're an experienced Python developer, you might have heard about Cython and its potential to significantly boost Python's performance. In this tutorial, we'll explore what Cython is, how it relates to C, and why it's relevant for Python developers.
19+
20+
What is Cython?
21+
---------------
22+
23+
Cython is an open-source programming language and compiler that makes it easy to write Python code that runs as fast as C. It's designed to bridge the gap between Python's ease of use and C's performance. Cython allows you to write code using Python syntax while taking advantage of C's performance optimizations. This makes it an attractive choice for tasks that require high performance, such as numerical computations, scientific simulations, and more.
24+
25+
Python and C: A Powerful Combination
26+
-------------------------------------
27+
28+
Python is a high-level programming language known for its simplicity and readability. However, it's an interpreted language, which can sometimes lead to slower execution speeds, especially for computationally intensive tasks. C, on the other hand, is a low-level programming language that is compiled directly into machine code, resulting in faster execution speeds.
29+
30+
Cython bridges this gap by allowing you to write code that looks like Python but gets compiled into C, providing the best of both worlds. This combination enables Python developers to achieve performance similar to C while maintaining the ease of use and readability of Python.
31+
32+
Proving the Concept: Performance Comparison
33+
--------------------------------------------
34+
35+
To illustrate the performance benefits of using Cython, I've prepared a sample Python program that calculates Fibonacci numbers. I've implemented the Fibonacci calculation in both pure Python and Cython. The goal is to demonstrate how Cython's compilation into C code can lead to significant speed improvements.
36+
37+
Running the Experiment
38+
----------------------
39+
40+
In the ``test.py`` file included in this repository, I've set up a comparison between the Python and Cython implementations of the Fibonacci calculation. By measuring the execution time of each implementation, we can quantify the performance gain achieved through Cython.
41+
42+
To run the experiment yourself, follow these steps:
43+
44+
#. Clone this repository to your local machine.
45+
46+
.. code-block:: bash
47+
48+
git clone Cython-Tutorial
49+
50+
2. Navigate to the root directory of the repository.
51+
52+
.. code-block:: bash
53+
54+
cd Cython-Tutorial
55+
56+
3. Activate a virtual environment, and install the dependencies.
57+
58+
.. code-block:: bash
59+
60+
python -m venv venv
61+
source venv/Scripts/activate
62+
pip install -r requirements.txt
63+
64+
3. Build the Cython module.
65+
66+
.. code-block:: bash
67+
68+
python setup.py build_ext --inplace
69+
70+
4. Run the experiment.
71+
72+
.. code-block:: bash
73+
74+
python test.py
75+
76+
Results
77+
-------
78+
79+
After running the experiment, we observed the following results:
80+
81+
.. code-block :: text
82+
83+
Python time for Fibonacci(30): Approximately 917.5 nanoseconds
84+
Cython time for Fibonacci(30): Approximately 115.4 nanoseconds
85+
86+
This comparison clearly shows that the Cython implementation outperforms the pure Python implementation by a significant margin. The faster execution time of the Cython implementation is a testament to Cython's ability to compile Python-like code into optimized C code.
87+
88+
Conclusion
89+
----------
90+
91+
In conclusion, Cython offers a powerful way to combine the convenience of Python with the performance benefits of C. By writing code that leverages Cython's compilation capabilities, Python developers can achieve faster execution times for computationally intensive tasks.
92+
93+
This repository serves as a proof of concept, showcasing the potential speed improvements that Cython can bring to Python code. We encourage you to explore the code provided and dive deeper into the world of Cython to harness its performance benefits for your own projects.
94+
95+
Read More
96+
---------
97+
98+
- `Cython Documentation <https://cython.readthedocs.io/en/latest/>`_
99+
- `Cython on GitHub <https://github.com/cython/cython>`_
100+
- `Cython on PyPI <https://pypi.org/project/Cython/>`_
101+
- `Differences between Python and CPython (Jython, IronPython, PyPy) <https://stackoverflow.com/questions/17130975/python-vs-cpython>`_
102+
- `Dag Sverre Seljebotn. "Fast numerical computations with Cython." Proceedings of the 8th Python in Science Conference (SciPy 2009). <https://conference.scipy.org/proceedings/scipy2009/paper_2/full_text.pdf>`_

my_module.pxd

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
cdef int c_fibonacci(int n)

my_module.pyx

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
cdef int c_fibonacci(int n):
2+
cdef int a = 0
3+
cdef int b = 1
4+
cdef int i, temp
5+
6+
if n <= 0:
7+
return 0
8+
elif n == 1:
9+
return 1
10+
else:
11+
for i in range(2, n + 1):
12+
temp = b
13+
b = a + b
14+
a = temp
15+
return b
16+
17+
def fibonacci(int n):
18+
return c_fibonacci(n)

requirements.txt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
setuptools~=68.0.0
2+
Cython~=3.0.0

setup.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
from setuptools import setup
2+
from Cython.Build import cythonize
3+
4+
setup(
5+
ext_modules=cythonize(
6+
"my_module.pyx",
7+
compiler_directives={
8+
"language_level": "3",
9+
},
10+
)
11+
)

test.py

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
import time
2+
import my_module
3+
4+
n = 30
5+
num_runs = 1000
6+
7+
8+
def cython_fibonacci(n):
9+
return my_module.fibonacci(n)
10+
11+
12+
start_time = time.perf_counter_ns()
13+
cython_result = 0
14+
for _ in range(num_runs):
15+
cython_result = cython_fibonacci(n)
16+
end_time = time.perf_counter_ns()
17+
18+
cython_time = (end_time - start_time) / num_runs
19+
20+
print(f"Fibonacci({n}) =", cython_result)
21+
print(f"Cython time: {cython_time:.1f} ns")
22+
23+
24+
def python_fibonacci(n):
25+
if n <= 0:
26+
return 0
27+
elif n == 1:
28+
return 1
29+
else:
30+
a, b = 0, 1
31+
for _ in range(2, n + 1):
32+
a, b = b, a + b
33+
return b
34+
35+
36+
start_time = time.perf_counter_ns()
37+
python_result = 0
38+
for _ in range(num_runs):
39+
python_result = python_fibonacci(n)
40+
end_time = time.perf_counter_ns()
41+
42+
python_time = (end_time - start_time) / num_runs
43+
44+
print(f"Fibonacci({n}) =", python_result)
45+
print(f"Python time: {python_time:.1f} ns")

0 commit comments

Comments
 (0)
0