首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何改进Python扩展文件行的读取?

如何改进Python扩展文件行的读取?
EN

Stack Overflow用户
提问于 2019-05-22 15:17:29
回答 2查看 514关注 0票数 0

最初是在在Windows ()和Linux上,是否有其他可选的可移植算法实现从文件中读取行?上被问到的,但由于在国外太过封闭,所以我在这里尝试用一个更简洁的案例用法来缩小它的范围。

我的目标是用Python扩展实现我自己的Python文件读取模块,并使用行缓存策略。没有任何行缓存策略的纯Python算法实现如下:

代码语言:javascript
复制
# 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扩展实现:(请参阅此处包含行缓存策略的完整代码。)

代码语言:javascript
复制
// 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扩展代码打开文件并逐行读取:

代码语言:javascript
复制
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扩展代码fastfilepackage.FastFile和C++ 11 std::ifstream需要3秒来解析100 of的日志数据,而提供的std::ifstream实现则需要1秒。

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

我只是想知道我是否能够替换或改进这个Python扩展实现,从而缩短运行Python程序的3秒时间。

我用这个来做基准测试:

代码语言:javascript
复制
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. 用C语言逐行读取文件
  2. 改进C++的逐行读取文件?
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-05-22 15:59:44

逐行阅读将在这里造成不可避免的减速。Python内置的面向文本的只读文件对象实际上有三层:

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

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

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

解决方案是大致像io.TextIOWrapper所做的那样:以块(而不是行)读取,并对它们进行批量解码(为下一个块保留不完整的UTF-8编码字符),然后搜索新行,从解码的缓冲区中提取子字符串,直到它耗尽为止(不要每次修剪缓冲区,只跟踪索引)。当解码缓冲区中不再保留完整的行时,修剪您已经生成的内容,然后读取、解码并追加一个新的块。

io.TextIOWrapper.readline上还有一些改进的余地(例如,每次读取块和间接调用时,他们都必须构造一个Python级别的int,因为它们不能保证自己正在包装BufferedReader),但这是重新实现您自己的方案的坚实基础。

更新:在检查完整代码(这与您发布的代码有很大不同)时,还存在其他问题。您的tp_iternext只是反复生成None,要求您调用对象来检索字符串。那是..。不幸的是。这比每个项目的Python解释器开销翻一番还多(tp_iternext调用起来很便宜,非常专业化;tp_call几乎不便宜,通过复杂的通用代码路径,要求解释器传递一个空的tuple,您从未使用过);另外-注意,PyFastFile_tp_call应该接受kwds的第三个参数,您忽略了这个参数,但仍然必须接受;对ternaryfunc的转换可以消除错误,但在某些平台上会中断)。

最后的注意事项(除了最小的文件外,与所有文件的性能无关):tp_iternext的契约不要求您在迭代器耗尽时设置异常,只需要设置return NULL;。您可以删除对PyErr_SetNone( PyExc_StopIteration );的调用;只要没有设置其他异常,return NULL;就可以单独指示迭代的结束,因此您可以通过根本不设置它来节省一些工作。

票数 2
EN

Stack Overflow用户

发布于 2019-05-24 00:47:51

这些结果只适用于Linux或Cygwin编译器。如果您正在使用Visual Studio Compiler,则std::getlinestd::ifstream.getline的结果是100%或比PythonBuildingfor line in file迭代器慢。

您将看到在代码中使用linecache.push_back( emtpycacheobject ),因为这样我只对用于读取行的时间进行基准测试,不包括将输入字符串转换为Python对象所花费的时间。因此,我注释掉了所有调用PyUnicode_DecodeUTF8的行。

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

代码语言:javascript
复制
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 getline的所有Python和C++代码,它应该会获得一些更高的性能:

代码语言:javascript
复制
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;
}

通过使用C++,我还设法将20%性能提高到仅比内置的Python for line in file

代码语言:javascript
复制
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();
}

最后,通过缓存作为输入的10%,我还获得了比内置Python for line in file更慢的10%性能:

代码语言:javascript
复制
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 getline的性能比Python内置for line in file低10%

代码语言:javascript
复制
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%:

代码语言:javascript
复制
$ /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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56260096

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档