Skip to main content
 首页 » 编程设计

python之针对 python 2 与 python 3 编译时,Cython 代码运行速度慢 125 倍

2025年04月02日9EasonJim

我有一大块 Cython 代码正在解析 Touchstone files我想使用 Python 2 和 Python 3。我正在使用非常 C 风格的解析技术来实现我认为的最高效率,包括手动 malloc-ing 和 free-ing char*使用 bytes 这样我就可以避免 GIL。编译时使用

python        3.5.2             0    anaconda 
cython        0.24.1       py35_0    anaconda 

我看到了令我满意的速度,小文件的速度适度提升(快约 20%),大文件的速度大幅提升(快约 2.5x)。编译时

python        2.7.12            0    anaconda 
cython        0.24.1       py27_0    anaconda 

它的运行速度大约慢了 125 倍(Python 3 中约 17 毫秒,Python 2 中约 2.2 秒)。它是使用非常简单的 setuputils 脚本在不同环境中编译的完全相同的代码。我目前没有使用 Cython 的 NumPy 进行任何解析或数据存储。

import cython 
cimport cython 
 
from cython cimport array 
import array 
 
from libc.stdlib cimport strtod, malloc, free 
from libc.string cimport memcpy 
 
ctypedef long long int64_t  # Really VS2008? Couldn't include this by default? 
 
# Bunch of definitions and utility functions omitted 
 
@cython.boundscheck(False) 
cpdef Touchstone parse_touchstone(bytes file_contents, int num_ports): 
    cdef: 
        char c 
        char* buffer = <char*> file_contents 
        int64_t length_of_buffer = len(file_contents) 
        int64_t i = 0 
 
        # These are some cpdef enums 
        FreqUnits freq_units 
        Domain domain 
        Format fmt 
        double z0 
        bint option_line_found = 0 
 
        array.array data = array.array('d') 
        array.array row = array.array('d', [0 for _ in range(row_size)]) 
 
    while i < length_of_buffer: 
        c = buffer[i]  # cdef char c 
        if is_whitespace(c): 
            i += 1 
            continue 
 
        if is_comment_char(c): 
            # Returns the last index of the comment 
            i = parse_comment(buffer, length_of_buffer) 
            continue 
 
        if not option_line_found and is_option_leader_char(c): 
            # Returns the last index of the option line 
            # assigns values of all references passed in 
            i = parse_option_line( 
                buffer, length_of_buffer, i, 
                &domain, &fmt, &z0, &freq_units) 
            if i < 0: 
                # Lots of boring code along the lines of 
                # if i == some_int: 
                #     raise Exception("message") 
                # I did this so that only my top-level parse has to interact 
                # with the interpreter, all the lower level functions have nogil 
            option_line_found = 1 
 
        if option_line_found: 
            if is_digit(c): 
                # Parse a float 
                row[row_idx] = strtod(buffer + i, &end_of_value) 
                # Jump the cursor to the end of that float 
                i = end_of_value - p - 1 
                row_idx += 1 
                if row_idx == row_size: 
                    # append this row onto the main data array 
                    data.extend(row) 
                    row_idx = 0 
 
        i += 1 
 
    return Touchstone(num_ports, domain, fmt, z0, freq_units, data) 

我已经排除了一些事情,例如类型转换。我还测试了代码在什么地方简单地遍历整个文件什么都不做。要么 Cython 对其进行了优化,要么它非常快,因为它导致 parse_touchstone 甚至不会出现在 cProfile/pstats 报告中。在我在最后一个 if row_idx == row_size 中输入打印语句后,我确定这不仅仅是注释、空格和选项行解析(未显示的是明显更复杂的关键字值解析) block 打印出一个状态,发现它需要大约 0.5-1 秒(猜测)来解析一个包含 512 个 float 的行。这真的不应该花这么长时间,尤其是在使用 strtod 进行解析时。我还检查了仅解析 2 行的值然后跳出 while 循环,它告诉我解析注释、空格和选项行占用了大约 800 毫秒(总时间的 1/3),那是为了6 行文本总计少于 150 字节。

我是不是漏掉了什么?是否有一个小技巧会导致 Cython 代码在 Python 2 中的运行速度比 Python 3 慢 3 个数量级?

(注意:我没有在这里显示完整的代码,因为出于法律原因我不确定我是否被允许这样做,而且总共大约有 450 行)

请您参考如下方法:

问题出在 strtod 上,它不是 optimized in VS2008 .显然,每次调用时它都会在内部计算输入字符串的长度,如果您使用长字符串调用它,这将大大降低您的代码速度。为了避免这种情况,您必须围绕 strtod 编写一个包装器以一次仅使用小缓冲区(有关如何执行此操作的示例,请参见上面的链接)或编写您自己的 strtod函数。