编程语言
首页 > 编程语言> > python – Cython中complex.real和creal(复杂)之间的区别

python – Cython中complex.real和creal(复杂)之间的区别

作者:互联网

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

考虑以下示例:

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方法相比.通过将代码放在一个
使用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兼容).
因此,我创建了一个等效的纯C函数来检查任何可能的
与c.real和c.imag相比的收益:

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.real和c.imag已经足够快了.

标签:python,cython,complex-numbers,complextype
来源: https://codeday.me/bug/20190622/1264096.html