python - Cython 中 complex.real 和 creal(complex) 的区别

标签 python cython complex-numbers complextype

为了在 cython 中将实部与复部分开,我通常使用 complex.realcomplex.imag 来完成这项工作。然而,这确实会在 html 输出中生成颜色为“python red”的代码,我想我应该使用 creal(complex)cimag (复杂) 代替。

考虑下面的例子:

cdef double complex myfun():
    cdef double complex c1,c2,c3
    c1=1.0 + 1.2j
    c2=2.2 + 13.4j
    c3=c2.real + c1*c2.imag
    c3=creal(c2) + c1*c2.imag
    c3=creal(c2) + c1*cimag(c2)
    return c2

c3 的赋值给:

__pyx_v_c3 = __Pyx_c_sum(__pyx_t_double_complex_from_parts(__Pyx_CREAL(__pyx_v_c2), 0), __Pyx_c_prod(__pyx_v_c1, __pyx_t_double_complex_from_parts(__Pyx_CIMAG(__pyx_v_c2), 0)));

__pyx_v_c3 = __Pyx_c_sum(__pyx_t_double_complex_from_parts(creal(__pyx_v_c2), 0), __Pyx_c_prod(__pyx_v_c1, __pyx_t_double_complex_from_parts(__Pyx_CIMAG(__pyx_v_c2), 0)));

__pyx_v_c3 = __Pyx_c_sum(__pyx_t_double_complex_from_parts(creal(__pyx_v_c2), 0), __Pyx_c_prod(__pyx_v_c1, __pyx_t_double_complex_from_parts(cimag(__pyx_v_c2), 0)));

第一行使用(python 色)构造__Pyx_CREAL__Pyx_CIMAG

这是为什么,它会“显着”影响性能吗?

最佳答案

肯定是默认的C库 ( complex.h ) 会起作用 给你。

但是,这个库似乎不会给你任何显着的改进 与 c.real c.imag 方法相比。通过将代码放在 with nogil: block ,你可以检查你的代码是否已经没有调用 Python API:

cdef double complex c1, c2, c3
with nogil:
    c1 = 1.0 + 1.2j
    c2 = 2.2 + 13.4j
    c3 = c2.real + c1*c2.imag

我使用的是 Windows 7 和 Python 2.7,其中没有可用的 complex.h Visual Studio 编译器 9.0 的内置 C 库(与 Python 2.7 兼容)。 因此,我创建了一个 equivalet 纯 C 函数来检查任何可能的 与 c.realc.imag 相比的 yield :

cdef double mycreal(double complex dc):
    cdef double complex* dcptr = &dc
    return (<double *>dcptr)[0]

cdef double mycimag(double complex dc):
    cdef double complex* dcptr = &dc
    return (<double *>dcptr)[1]

运行以下两个测试函数后:

def myfun1(double complex c1, double complex c2):
    return c2.real + c1*c2.imag

def myfun2(double complex c1, double complex c2):
    return mycreal(c2) + c1*mycimag(c2)

得到时间:

In [3]: timeit myfun1(c1, c2)
The slowest run took 17.50 times longer than the fastest. This could mean that a
n intermediate result is being cached.
10000000 loops, best of 3: 86.3 ns per loop

In [4]: timeit myfun2(c1, c2)
The slowest run took 17.24 times longer than the fastest. This could mean that a
n intermediate result is being cached.
10000000 loops, best of 3: 87.6 ns per loop

确认 c.realc.imag 已经足够快了。

关于python - Cython 中 complex.real 和 creal(complex) 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46361850/

相关文章:

python - 使用电子邮件库获取正文名称

python - 为 python 模块创建 .pxd 文件

python - 如何在 Cython 中包装匿名枚举并为其命名?

python - 尝试抓取,找回[]

c++ - 提升 python : how to call a C++ virtual function

Python 列表重复整个列表的最后一个元素

python - 找不到 cython 库

javascript - 在 JavaScript 中是否可以定义负数的平方根?

python - 格式化复数

使用 complex.h 库在 Visual Studio 2013 中编译 C 代码