为了在 cython 中将实部与复部分开,我通常使用 complex.real
和 complex.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.real
和 c.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.real
和 c.imag
已经足够快了。
关于python - Cython 中 complex.real 和 creal(complex) 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46361850/