gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 07:47:01 25 4
gpt4 key购买 nike

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

我的目标是使用具有行缓存策略的 Python C 扩展实现我自己的 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

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

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

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

我用它来做基准测试:

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
  2. Improving C++'s reading file line by line?

最佳答案

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

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

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

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

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

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

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

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

关于python - 如何改进 Python C Extensions 文件行读取?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56260096/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com