如何改进 Python C Extensions 文件行读取?

How to improve Python C Extensions file line reading?

最初在 Are there alternative and portable algorithm implementation for reading lines from a file on Windows (Visual Studio Compiler) and Linux? 上问过,但因为太国外而关闭了,那么,我在这里试图通过更简洁的案例用法来缩小其范围。

我的目标是使用 Python C Extensions 和行缓存策略为 Python 实现我自己的文件读取模块。没有任何行缓存策略的纯Python算法实现是这样的:

# This takes 1 second to parse 100MB of log data
with open('myfile', 'r', errors='replace') as myfile:
    for line in myfile:
        if 'word' in line: 
            pass

恢复 Python C 扩展实现:(see here the full code with line caching policy)

// other code to open the file on the std::ifstream object and create the iterator
...

static PyObject * PyFastFile_iternext(PyFastFile* self, PyObject* args)
{
    std::string newline;

    if( std::getline( self->fileifstream, newline ) ) {
        return PyUnicode_DecodeUTF8( newline.c_str(), newline.size(), "replace" );
    }

    PyErr_SetNone( PyExc_StopIteration );
    return NULL;
}

static PyTypeObject PyFastFileType =
{
    PyVarObject_HEAD_INIT( NULL, 0 )
    "fastfilepackage.FastFile" /* tp_name */
};

// create the module
PyMODINIT_FUNC PyInit_fastfilepackage(void)
{
    PyFastFileType.tp_iternext = (iternextfunc) PyFastFile_iternext;
    Py_INCREF( &PyFastFileType );

    PyObject* thismodule;
    // other module code creating the iterator and context manager
    ...

    PyModule_AddObject( thismodule, "FastFile", (PyObject *) &PyFastFileType );
    return thismodule;
}

这是 Python 代码,它使用 Python C 扩展代码打开一个文件并逐行读取它的行:

from fastfilepackage import FastFile

# This takes 3 seconds to parse 100MB of log data
iterable = fastfilepackage.FastFile( 'myfile' )
for item in iterable:
    if 'word' in iterable():
        pass

现在 Python C 扩展代码 fastfilepackage.FastFile 和 C++ 11 std::ifstream 需要 3 秒来解析 100MB 的日志数据,而 Python 实现需要 1 秒第二。

文件myfile的内容只是log lines,每行大约100~300个字符。字符只是 ASCII(模块 % 256),但由于记录器引擎上的错误,它可以放置无效的 ASCII 或 Unicode 字符。因此,这就是我在打开文件时使用 errors='replace' 策略的原因。

我只是想知道我是否可以替换或改进这个 Python C 扩展实现,将 3 秒的时间减少到 运行 Python 程序。

我用它来做基准测试:

import time
import datetime
import fastfilepackage

# usually a file with 100MB
testfile = './myfile.log'

timenow = time.time()
with open( testfile, 'r', errors='replace' ) as myfile:
    for item in myfile:
        if None:
            var = item

python_time = time.time() - timenow
timedifference = datetime.timedelta( seconds=python_time )
print( 'Python   timedifference', timedifference, flush=True )
# prints about 3 seconds

timenow = time.time()
iterable = fastfilepackage.FastFile( testfile )
for item in iterable:
    if None:
        var = iterable()

fastfile_time = time.time() - timenow
timedifference = datetime.timedelta( seconds=fastfile_time )
print( 'FastFile timedifference', timedifference, flush=True )
# prints about 1 second

print( 'fastfile_time %.2f%%, python_time %.2f%%' % ( 
        fastfile_time/python_time, python_time/fastfile_time ), flush=True )

相关问题:

  1. Reading file Line By Line in C

逐行阅读将不可避免地导致速度变慢。 Python的built-in面向文本的read-only文件对象实际上是三层:

  1. io.FileIO - 对文件的原始、无缓冲访问
  2. io.BufferedReader - 缓冲底层 FileIO
  3. io.TextIOWrapper - 包装 BufferedReader 以实现对 str
  4. 的缓冲解码

虽然 iostream 确实执行缓冲,但它只是在执行 io.BufferedReader 的工作,而不是 io.TextIOWrapperio.TextIOWrapper 添加额外的缓冲层,从 BufferedReader 中读取 8 KB 并将它们批量解码为 str (当一个块结束时在一个不完整的字符中,它会保存剩余的字节以添加到下一个块中),然后根据请求从解码块中产生单独的行直到它用完(当解码块以部分行结束时,其余部分添加到下一个块中)解码块)。

相比之下,您使用 std::getline 一次消耗一行,然后使用 PyUnicode_DecodeUTF8 一次解码一行,然后返回给调用者;当调用者请求下一行时,至少有一些与您的 tp_iternext 实现相关的代码已经离开 CPU 缓存(或者至少离开了缓存中最快的部分)。将 8 KB 文本解码为 UTF-8 的紧密循环会非常快;反复离开循环并且一次只解码 100-300 个字节会变慢。

解决方案大致是做 io.TextIOWrapper 做的事情:读取块,而不是行,并批量解码它们(为下一个块保留不完整的 UTF-8 编码字符),然后搜索换行符以从解码缓冲区中取出子字符串,直到用尽(不要每次 trim 缓冲区,只跟踪索引)。当解码缓冲区中不再有完整的行时,trim 您已经生成的内容,并读取、解码和附加一个新块。

Python's underlying implementation of io.TextIOWrapper.readline上有一些改进的空间(例如,他们必须在每次读取一个块并间接调用时构建一个Python级别int,因为他们不能保证他们包装了一个 BufferedReader),但它是重新实现您自己的方案的坚实基础。

更新: 在检查您的完整代码(与您发布的完全不同)时,您遇到了其他问题。您的 tp_iternext 只是反复产生 None,需要您 调用 您的对象来检索字符串。那真不幸。这是每个项目的 Python 解释器开销的两倍多(tp_iternext 调用起来很便宜,非常专业;tp_call 几乎没有那么便宜,通过复杂的通用代码路径,需要解释器传递你从未使用过的空 tuple 参数;side-note、PyFastFile_tp_call 应该接受 kwds 的第三个参数,你忽略它,但必须仍然被接受;投射到 ternaryfunc 会消除错误,但这会在某些平台上中断)。

最后说明(除了最小文件外,与所有性能无关):tp_iternext 的合同不要求您在迭代器耗尽时设置异常,只是您 return NULL;.您可以删除对 PyErr_SetNone( PyExc_StopIteration ); 的呼叫;只要没有设置其他异常,return NULL; 单独表示迭代结束,因此您可以通过根本不设置它来节省一些工作。

这些结果仅适用于 Linux 或 Cygwin 编译器。如果您使用 Visual Studio Compilerstd::getlinestd::ifstream.getline 的结果是 100% 或比 Python 内置 for line in file 迭代器更慢。

您会看到代码周围使用了 linecache.push_back( emtpycacheobject ),因为通过这种方式,我只对用于读取行的时间进行基准测试,不包括 Python 将输入字符串转换为 Python Unicode 对象。因此,我注释掉了所有调用 PyUnicode_DecodeUTF8.

的行

这些是示例中使用的全局定义:

const char* filepath = "./myfile.log";
size_t linecachesize = 131072;

PyObject* emtpycacheobject;
emtpycacheobject = PyUnicode_DecodeUTF8( "", 0, "replace" );

我设法优化了我的 Posix C getline 用法(通过缓存总缓冲区大小而不是始终传递 0),现在 Posix C getline 节拍5% 的 Python 内置 for line in file。我想如果我删除 Posix C getline 周围的所有 Python 和 C++ 代码,它应该会获得更多性能:

char* readline = (char*) malloc( linecachesize );
FILE* cfilestream = fopen( filepath, "r" );

if( cfilestream == NULL ) {
    std::cerr << "ERROR: Failed to open the file '" << filepath << "'!" << std::endl;
}

if( readline == NULL ) {
    std::cerr << "ERROR: Failed to alocate internal line buffer!" << std::endl;
}

bool getline() {
    ssize_t charsread;
    if( ( charsread = getline( &readline, &linecachesize, cfilestream ) ) != -1 ) {
        fileobj.getline( readline, linecachesize );
        // PyObject* pythonobject = PyUnicode_DecodeUTF8( readline, charsread, "replace" );
        // linecache.push_back( pythonobject );
        // return true;

        Py_XINCREF( emtpycacheobject );
        linecache.push_back( emtpycacheobject );
        return true;
    }
    return false;
}

if( readline ) {
    free( readline );
    readline = NULL;
}

if( cfilestream != NULL) {
    fclose( cfilestream );
    cfilestream = NULL;
}

我还通过使用 std::ifstream.getline():

设法将 C++ 性能提高到仅比内置 Python C for line in file20%
char* readline = (char*) malloc( linecachesize );
std::ifstream fileobj;
fileobj.open( filepath );

if( fileobj.fail() ) {
    std::cerr << "ERROR: Failed to open the file '" << filepath << "'!" << std::endl;
}

if( readline == NULL ) {
    std::cerr << "ERROR: Failed to alocate internal line buffer!" << std::endl;
}

bool getline() {

    if( !fileobj.eof() ) {
        fileobj.getline( readline, linecachesize );
        // PyObject* pyobj = PyUnicode_DecodeUTF8( readline, fileobj.gcount(), "replace" );
        // linecache.push_back( pyobj );
        // return true;

        Py_XINCREF( emtpycacheobject );
        linecache.push_back( emtpycacheobject );
        return true;
    }
    return false;
}

if( readline ) {
    free( readline );
    readline = NULL;
}

if( fileobj.is_open() ) {
    fileobj.close();
}

最后,通过缓存它使用的 std::string,我还设法获得了 10% 比内置 Python C for line in filestd::getline 慢的性能作为输入:

std::string line;
std::ifstream fileobj;
fileobj.open( filepath );

if( fileobj.fail() ) {
    std::cerr << "ERROR: Failed to open the file '" << filepath << "'!" << std::endl;
}

try {
    line.reserve( linecachesize );
}
catch( std::exception error ) {
    std::cerr << "ERROR: Failed to alocate internal line buffer!" << std::endl;
}

bool getline() {

    if( std::getline( fileobj, line ) ) {
        // PyObject* pyobj = PyUnicode_DecodeUTF8( line.c_str(), line.size(), "replace" );
        // linecache.push_back( pyobj );
        // return true;

        Py_XINCREF( emtpycacheobject );
        linecache.push_back( emtpycacheobject );
        return true;
    }
    return false;
}

if( fileobj.is_open() ) {
    fileobj.close();
}

从 C++ 中删除所有样板后,Posix C getline 的性能比 Python 内置 for line in file:

低 10%
const char* filepath = "./myfile.log";
size_t linecachesize = 131072;

PyObject* emtpycacheobject = PyUnicode_DecodeUTF8( "", 0, "replace" );
char* readline = (char*) malloc( linecachesize );
FILE* cfilestream = fopen( filepath, "r" );

static PyObject* PyFastFile_tp_call(PyFastFile* self, PyObject* args, PyObject *kwargs) {
    Py_XINCREF( emtpycacheobject );
    return emtpycacheobject;
}

static PyObject* PyFastFile_iternext(PyFastFile* self, PyObject* args) {
    ssize_t charsread;
    if( ( charsread = getline( &readline, &linecachesize, cfilestream ) ) == -1 ) {
        return NULL;
    }
    Py_XINCREF( emtpycacheobject );
    return emtpycacheobject;
}

static PyObject* PyFastFile_getlines(PyFastFile* self, PyObject* args) {
    Py_XINCREF( emtpycacheobject );
    return emtpycacheobject;
}

static PyObject* PyFastFile_resetlines(PyFastFile* self, PyObject* args) {
    Py_INCREF( Py_None );
    return Py_None;
}

static PyObject* PyFastFile_close(PyFastFile* self, PyObject* args) {
    Py_INCREF( Py_None );
    return Py_None;
}

上次测试的值 运行 其中 Posix C getline 比 Python 低 10%:

$ /bin/python3.6 fastfileperformance.py fastfile_time 1.15%, python_time 0.87%
Python   timedifference 0:00:00.695292
FastFile timedifference 0:00:00.796305

$ /bin/python3.6 fastfileperformance.py fastfile_time 1.13%, python_time 0.88%
Python   timedifference 0:00:00.708298
FastFile timedifference 0:00:00.803594

$ /bin/python3.6 fastfileperformance.py fastfile_time 1.14%, python_time 0.88%
Python   timedifference 0:00:00.699614
FastFile timedifference 0:00:00.795259

$ /bin/python3.6 fastfileperformance.py fastfile_time 1.15%, python_time 0.87%
Python   timedifference 0:00:00.699585
FastFile timedifference 0:00:00.802173

$ /bin/python3.6 fastfileperformance.py fastfile_time 1.15%, python_time 0.87%
Python   timedifference 0:00:00.703085
FastFile timedifference 0:00:00.807528

$ /bin/python3.6 fastfileperformance.py fastfile_time 1.17%, python_time 0.85%
Python   timedifference 0:00:00.677507
FastFile timedifference 0:00:00.794591

$ /bin/python3.6 fastfileperformance.py fastfile_time 1.20%, python_time 0.83%
Python   timedifference 0:00:00.670492
FastFile timedifference 0:00:00.804689