- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
最初在 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 )
相关问题:
最佳答案
逐行阅读将不可避免地导致速度变慢。 Python内置的面向文本的只读文件对象实际上是三层:
io.FileIO
- 对文件的原始、无缓冲访问io.BufferedReader
- 缓冲底层 FileIO
io.TextIOWrapper
- 包装 BufferedReader
对 str
实现缓冲解码同时 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/
猫f1.txt阿曼维沙尔阿杰贾伊维杰拉胡尔曼尼什肖比特批评塔夫林现在输出应该符合上面给定的条件 最佳答案 您可以在文件读取循环中设置一个计数器并打印它, 计数=0 读取行时做 让我们数一数++ if
我正在尝试查找文件 1 和文件 2 中的共同行。如果公共(public)行存在,我想写入文件 2 中的行,否则打印文件 1 中的非公共(public)行。fin1 和 fin2 是这里的文件句柄。它读
我有这个 SQL 脚本: CREATE TABLE `table_1` ( `IDTable_1` int(11) NOT NULL, PRIMARY KEY (`IDTable_1`) );
我有 512 行要插入到数据库中。我想知道提交多个插入内容是否比提交一个大插入内容有任何优势。例如 1x 512 行插入 -- INSERT INTO mydb.mytable (id, phonen
如何从用户中选择user_id,SUB(row, row - 1),其中user_id=@userid我的表用户,id 为 1、3、4、10、11、23...(不是++) --id---------u
我曾尝试四处寻找解决此问题的最佳方法,但我找不到此类问题的任何先前示例。 我正在构建一个基于超本地化的互联网购物中心,该区域分为大约 3000 个区域。每个区域包含大约 300 个项目。它们是相似的项
preg_match('|phpVersion = (.*)\n|',$wampConfFileContents,$result); $phpVersion = str_replace('"','',
我正在尝试创建一个正则表达式,使用“搜索并替换全部”删除 200 个 txt 文件的第一行和最后 10 行 我尝试 (\s*^(\h*\S.*)){10} 删除包含的前 10 行空白,但效果不佳。 最
下面的代码从数据库中获取我需要的信息,但没有打印出所有信息。首先,我知道它从表中获取了所有正确的信息,因为我已经在 sql Developer 中尝试过查询。 public static void m
很难说出这里问的是什么。这个问题是含糊的、模糊的、不完整的、过于宽泛的或修辞性的,无法以目前的形式得到合理的回答。如需帮助澄清此问题以便重新打开它,visit the help center 。 已关
我试图在两个表中插入记录,但出现异常。您能帮我解决这个问题吗? 首先我尝试了下面的代码。 await _testRepository.InsertAsync(test); await _xyzRepo
这个基本的 bootstrap CSS 显示 1 行 4 列: Text Text Text
如果我想从表中检索前 10 行,我将使用以下代码: SELECT * FROM Persons LIMIT 10 我想知道的是如何检索前 10 个结果之后的 10 个结果。 如果我在下面执行这段代码,
今天我开始使用 JexcelApi 并遇到了这个:当您尝试从特定位置获取元素时,不是像您通常期望的那样使用sheet.getCell(row,col),而是使用sheet.getCell(col,ro
我正在尝试在我的网站上开发一个用户个人资料系统,其中包含用户之前发布的 3 个帖子。我可以让它选择前 3 条记录,但它只会显示其中一条。我是不是因为凌晨 2 点就想编码而变得愚蠢? query($q)
我在互联网上寻找答案,但找不到任何答案。 (我可能问错了?)我有一个看起来像这样的表: 我一直在使用查询: SELECT title, date, SUM(money) FROM payments W
我有以下查询,我想从数据库中获取 100 个项目,但 host_id 多次出现在 urls 表中,我想每个 host_id 从该表中最多获取 10 个唯一行。 select * from urls j
我的数据库表中有超过 500 行具有特定日期。 查询特定日期的行。 select * from msgtable where cdate='18/07/2012' 这将返回 500 行。 如何逐行查询
我想使用 sed 从某一行开始打印 n 行、跳过 n 行、打印 n 行等,直到文本文件结束。例如在第 4 行声明,打印 5-9,跳过 10-14,打印 15-19 等 来自文件 1 2 3 4 5 6
我目前正在执行验证过程来检查用户的旧密码,但问题是我无法理解为什么我的查询返回零行,而预期它有 1 行。另一件事是,即使我不将密码文本转换为 md5,哈希密码仍然得到正确的答案,但我不知道为什么会发生
我是一名优秀的程序员,十分优秀!