相关疑难解决方法(0)

真实文件对象比 StringIO 和 cStringIO 慢?

StringIO其代码中有以下注释:

Notes:
- Using a real file is often faster (but less convenient).
- There's also a much faster implementation in C, called cStringIO, but
  it's not subclassable.
Run Code Online (Sandbox Code Playgroud)

“真实文件通常更快”这句话对我来说真的很奇怪:写入磁盘怎么能胜过写入内存呢?我尝试分析这些不同的案例,得到的结果与这些文档以及这个问题的答案相矛盾。这个另一个问题确实解释了为什么 cStringIO 在某些情况下速度较慢,尽管我在这里没有进行任何连接。该测试将给定量的数据写入文件,然后查找开头并将其读回。在“新”测试中,我每次都创建一个新对象,而在“相同”测试中,我会截断并为每次重复重用相同的对象,以排除开销来源。对于使用数据量较小但数据量较大的临时文件来说,这种开销很重要。

代码在这里。

Using 1000 passes with size 1.0KiB
New StringIO:   0.0026 0.0025 0.0034
Same StringIO:  0.0026 0.0023 0.0030
New cStringIO:  0.0009 0.0010 0.0008
Same cStringIO: 0.0009 0.0009 0.0009
New tempfile:   0.0679 0.0554 0.0542
Same tempfile:  0.0069 0.0064 0.0070
==============================================================
Using 1000 passes with …
Run Code Online (Sandbox Code Playgroud)

python performance temporary-files stringio cstringio

3
推荐指数
1
解决办法
626
查看次数