<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom"><channel><title>性能优化 :: 标签 :: yafeng 的博客</title><link>http://yafengabc.github.io/tags/%E6%80%A7%E8%83%BD%E4%BC%98%E5%8C%96/index.html</link><description/><generator>Hugo</generator><language>zh-cn</language><lastBuildDate>Sat, 19 Sep 2026 14:13:35 +0800</lastBuildDate><atom:link href="http://yafengabc.github.io/tags/%E6%80%A7%E8%83%BD%E4%BC%98%E5%8C%96/index.xml" rel="self" type="application/rss+xml"/><item><title>用Cython加速Python程序以及包装C程序简单测试</title><link>http://yafengabc.github.io/cnblogs/p6130849/index.html</link><pubDate>Sun, 04 Dec 2016 15:02:00 +0800</pubDate><guid>http://yafengabc.github.io/cnblogs/p6130849/index.html</guid><description>用Cython加速Python程序 我没有拼错，就是Cython，C+Python=Cython!&#10;我们来看看Cython的威力,先运行下边的程序：&#10;import time&#10;def fib(n):&#10;if n0:&#10;return 0&#10;if n1:&#10;return 1&#10;return fib(n-1)+fib(n-2)&#10;t=time.time()&#10;print(fib(40))&#10;print(time.time()-t)&#10;$ python fib.py&#10;102334155&#10;59.367255449295044&#10;在我的渣渣笔记本上，用时59.3秒，差不多一分钟。当然，在你那可能比我快一点，这也很正常。&#10;好了，我们再试试Cython：&#10;$ cython fib.py –embed&#10;$ gcc -O3 fib.c -I /usr/include/python3.5m/ -lpython3.5m&#10;$ ./a.out&#10;102334155&#10;14.487313747406006&#10;嗯，快了那么一点点，4倍左右;我解释一下前边的几句代码：&#10;首先，用cython命令把python生成c文件，也就是cython fib.py会生成一个fib.c的文件&#10;–embed参数就是自动生成一个main函数，以便让gcc生成可执行程序。&#10;接下来就是用gcc把fib.c编译成了个a.out程序，运行之，结果快了4倍（从60秒减少到15秒以内）。&#10;当然，这只是小试牛刀，区区4倍而已，这也太少了！&#10;接下来我吧这个文件复制成fib.pyx，并修改了一句代码：&#10;import time&#10;cdef int fib(int n):&#10;if n0:&#10;return 0&#10;if n1:&#10;return 1&#10;return fib(n-1)+fib(n-2)&#10;t=time.time()&#10;print(fib(40))&#10;print(time.time()-t)</description></item></channel></rss>