Cython:如何在没有GIL的情况下打印

Beh*_*ali 6 python cython cythonize

如何print在没有gil的Cython函数中使用?例如:

from libc.math cimport log, fabs
cpdef double f(double a, double b) nogil:
    cdef double c = log( fabs(a - b) )
    print c
    return c
Run Code Online (Sandbox Code Playgroud)

编译时出现此错误:

Error compiling Cython file:
...
    print c
    ^
------------------------------------------------------------

Python print statement not allowed without gil
...
Run Code Online (Sandbox Code Playgroud)

我知道如何使用C库而不是他们的python等价物(math例如这里的库),但我找不到类似的方法print.

Dav*_*idW 11

这是评论中讨论的后续行动,这些讨论表明这个问题是基于一个轻微的误解:总是值得考虑为什么需要释放GIL以及是否真的需要这样做.

从根本上说,GIL是每个线程持有的标志,用于指示是否允许调用Python API.简单地拿着旗帜不会让你失去任何表现.Cython通常在不使用Python API时速度最快,但这是因为它正在执行的操作,而不是因为它持有标志(即printf可能比Python快一点print,但printf在有或没有GIL的情况下运行相同的速度) .

你真正需要担心GIL的唯一一次是在使用多线程代码时,释放它会让其他Python线程有机会运行.(同样,如果你正在编写一个库而你不需要Python API,那么释放GIL可能是一个好主意,这样你的用户可以根据需要运行其他线程).

最后,如果你在一个nogil区块中,并且想要快速进行Python操作,你可以简单地做:

with gil:
    print c
Run Code Online (Sandbox Code Playgroud)

有可能它不会花费你太多的性能,它可以节省大量的编程工作.

  • @HardikSindhav 我知道你很生气,因为我指出了你大量发布的 ChatGPT 答案。然而这个答案比 ChatGPT 早了大约 5 年 (3认同)

小智 9

使用printf来自stdio:

from libc.stdio cimport printf
...
printf("%f\n", c)
Run Code Online (Sandbox Code Playgroud)