如何改进 Python C 扩展文件行读取
How to improve Python C Extensions file line reading?
最初被问到是否有替代和可移植的算法实现可以从Windows(Visual Studio Compiler)和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 扩展实现:(请参阅此处带有行缓存策略的完整代码)
// 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 C 扩展代码打开文件并逐行读取其行的 Python 代码:
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++ 11std::ifstream
的 Python C 扩展代码fastfilepackage.FastFile
需要 3 秒来解析 100MB 的日志数据,而呈现的 Python 实现需要 1 秒。
文件myfile
的内容只是log lines
,每行大约100~300个字符。这些字符只是 ASCII(模块 % 256),但由于记录器引擎上的错误,它可以放置无效的 ASCII 或 Unicode 字符。因此,这就是我在打开文件时使用errors='replace'
策略的原因。
我只是想知道我是否可以替换或改进这个 Python C 扩展实现,减少运行 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 )
相关问题:
- 在 C 语言中逐行读取文件
- 逐行改进C++的读取文件?
逐行阅读将导致不可避免的减速。Python 内置的面向文本的只读文件对象实际上是三层:
io.FileIO
- 对文件的原始、无缓冲访问io.BufferedReader
- 缓冲基础FileIO
io.TextIOWrapper
- 包装BufferedReader
以实现缓冲解码以str
虽然iostream
确实执行缓冲,但它只是在做io.BufferedReader
的工作,而不是io.TextIOWrapper
。io.TextIOWrapper
增加了一个额外的缓冲层,从BufferedReader
中读取 8 KB 的块并将它们批量解码为str
(当一个块以不完整的字符结尾时,它会保存剩余的字节以附加到下一个块),然后根据请求从解码的块中生成单独的行,直到它耗尽(当解码的块以部分行结尾时, 其余部分附加到下一个解码块之前)。
相比之下,你一次使用std::getline
使用一行,然后用PyUnicode_DecodeUTF8
一次解码一行,然后让回给调用者;当调用者请求下一行时,至少与你的tp_iternext
实现相关的一些代码已经离开了CPU缓存(或者至少, 留下缓存中最快的部分)。将 8 KB 文本解码为 UTF-8 的紧密循环将非常快;反复离开循环,一次只解码 100-300 个字节会更慢。
解决方案大致是执行io.TextIOWrapper
所做的操作:读取块,而不是行,并批量解码它们(为下一个块保留不完整的 UTF-8 编码字符),然后搜索换行符以从解码的缓冲区中捞出子字符串,直到它耗尽(不要每次都修剪缓冲区,只是跟踪索引)。当解码缓冲区中没有更多完整的行时,修剪已生成的内容,然后读取、解码和附加一个新块。
Python 的底层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;
单独表示迭代结束,因此您可以通过根本不设置来节省一些工作。
这些结果仅适用于 Linux 或 Cygwin 编译器。如果您使用的是Visual Studio Compiler
,则std::getline
和std::ifstream.getline
的结果比内置的 Pythonfor line in file
迭代器慢100%
或更慢。
您将看到围绕代码使用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 Cgetline
使用(通过缓存总缓冲区大小而不是总是传递 0),现在 Posix Cgetline
击败了 Python 内置for line in file
5%
。我想如果我删除所有 Python 并围绕 Posix Cgetline
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 Cfor line in file
慢20%
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
来获得比内置的 Python Cfor line in file
std::getline
慢10%
性能:
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 Cgetline
的性能比 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 Cgetline
比 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
- 正在将csv文件读取为双精度矢量
- 将从格式化文本文件读取的文本数据存储到链表
- C++ 读取文件读取文件不正确
- 使用对象文件读取三角形数据网格
- 如何减慢从 BVH 文件读取的 opengl 动画?
- 从文件读取,并写入函数C++中的数组
- 从对象C++中的文件读取内容时出现分段错误
- 从文件读取并通过矢量输出到控制台
- 尝试将字符串从文件读取到无符号字符向量中
- 如何将文本文件读取到二维数组中并以 c++ 打印
- 简化文件读取的函数
- 如何将逗号分隔的文件读取为 2D int 数组?
- 在 c++ 中将数据从文件读取到队列中
- 'std::wstring_convert'尽可能多地转换(从 UTF8 文件读取块)
- C++,从文件读取到结构,然后读取到向量(结构被推入向量太多次,而不仅仅是一次)
- 文件读取C++包括空格键
- 从文件读取时未将值推回矢量
- 从文件 C++ 读取时的无限循环
- 从同一文件读取和写入?
- 从.txt文件读取到C++中的双精度向量