You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何我的Cython代码运行速度比C代码更快?

Cython代码

该Cython代码来自Cython官方文档。

# myfunc.pyx
cdef double f(double x) except ? -2:
    return x ** 2 - x

def integrate_f(double a, double b, int N):
    cdef int i
    cdef double s
    cdef double dx
    s = 0
    dx = (b - a) / N
    for i in range(N):
        s += f(a + i * dx)
    return s * dx
# main.py
from myfunc import integrate_f
import time

if __name__ == "__main__":
    t = time.time()
    integrate_f(1,11,1000000)
    print("Cython Used Time: ", time.time() - t, " s")
# setup.py
from setuptools import setup
from Cython.Build import cythonize

setup(
    name='myfunc app',
    ext_modules=cythonize("myfunc.pyx"),
)

执行步骤:

  • 首先在终端执行命令:python setup.py build_ext --inplace
  • 随后执行:python main.py

C代码
# test.c
#include<stdio.h>
#include <stdlib.h>
#include<sys/time.h>

double f(double x){
    return x*x - x;
}

double integrate_f(double a, double b, int N){
    int i;
    double s;
    double dx;
    s = 0.0;
    dx = (b - a) / N;
    for(i=0; i < N; i++){
        s += f(a+i*dx);
    }
    return s*dx;
}

int main(){
    struct timeval tv_begin, tv_end;
    unsigned int  ulTime1 = 0,ulTime2 =0;
    gettimeofday(&tv_begin,NULL);
    
    integrate_f(1,11,1000000);

    gettimeofday(&tv_end,NULL);
    ulTime1 = tv_end.tv_sec*1000000 + tv_end.tv_usec;//microsecond
    ulTime2 = tv_begin.tv_sec*1000000 + tv_begin.tv_usec;//microsecond
    printf("C Used Time: %d um\n",ulTime1-ulTime2);
    return 0;
}

执行步骤:

  • 首先在终端执行命令:gcc test.c
  • 随后执行:./a.out

测试结果
Cython Used Time:  0.0012311935424804688 s
C Used Time: 7895 um

两段代码中f()函数均被调用1000000次,我原本认为C代码应比Cython代码更快,但实际结果并非如此。


内容的提问来源于stack exchange,提问作者Crown-Messi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 09:16:16