From 8131c17258b2612b3384a2d9fec42877ca0b5f35 Mon Sep 17 00:00:00 2001 From: guanjihuan Date: Tue, 29 Jul 2025 10:37:06 +0800 Subject: [PATCH] update --- 2025.07.28_programming_with_cython/a.py | 23 +++++++++++++++++++ .../example.pyx | 11 +++++++++ 2025.07.28_programming_with_cython/setup.py | 4 ++++ 3 files changed, 38 insertions(+) create mode 100644 2025.07.28_programming_with_cython/a.py create mode 100644 2025.07.28_programming_with_cython/example.pyx create mode 100644 2025.07.28_programming_with_cython/setup.py diff --git a/2025.07.28_programming_with_cython/a.py b/2025.07.28_programming_with_cython/a.py new file mode 100644 index 0000000..f6bcb06 --- /dev/null +++ b/2025.07.28_programming_with_cython/a.py @@ -0,0 +1,23 @@ +import example +import time + +def py_calculate(n): + result = 0 + for i in range(n): + result += i + return result + +n = 10**8 + +start = time.time() +py_result = py_calculate(n) +print(py_result) +py_time = time.time() - start + +start = time.time() +cy_result = example.calculate(n) +print(cy_result) +cy_time = time.time() - start + +print(f"Python 版本: {py_time:.6f} 秒") +print(f"Cython 版本: {cy_time:.6f} 秒") \ No newline at end of file diff --git a/2025.07.28_programming_with_cython/example.pyx b/2025.07.28_programming_with_cython/example.pyx new file mode 100644 index 0000000..4138362 --- /dev/null +++ b/2025.07.28_programming_with_cython/example.pyx @@ -0,0 +1,11 @@ +def calculate(int n): + cdef int i + + cdef long long result = 0 + # cdef int result = 0 # 这个类型在数值比较大的时候会溢出,结果不正确。 + # result = 0 # 这个不声明类型,使用 Python 的 int,Python 的整数是任意精度的,不会溢出,但性能会比 C 类型低。 + + for i in range(n): + result += i + + return result \ No newline at end of file diff --git a/2025.07.28_programming_with_cython/setup.py b/2025.07.28_programming_with_cython/setup.py new file mode 100644 index 0000000..91eeb91 --- /dev/null +++ b/2025.07.28_programming_with_cython/setup.py @@ -0,0 +1,4 @@ +from distutils.core import setup +from Cython.Build import cythonize + +setup(ext_modules=cythonize("example.pyx")) \ No newline at end of file