- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
在我分析 python 字符串方法的方式中,我可以使用最快的方法。我有这段代码来测试文件、StringIO、StringIO 和普通字符串中的字符串连接。
#!/usr/bin/env python
#title : pythonTiming.py
#description : Will be used to test timing function in python
#author : myusuf
#date : 19-11-2014
#version : 0
#usage :python pythonTiming.py
#notes :
#python_version :2.6.6
#==============================================================================
import time
import cStringIO
import StringIO
class Timer(object):
def __enter__(self):
self.start = time.time()
return self
def __exit__(self, *args):
self.end = time.time()
self.interval = self.end - self.start
testbuf = """ Hello This is a General String that will be repreated
This string will be written to a file , StringIO and a sregualr strin then see the best to handle string according to time
""" * 1000
MyFile = open("./testfile.txt" ,"wb+")
MyStr = ''
MyStrIo = StringIO.StringIO()
MycStrIo = cStringIO.StringIO()
def strWithFiles():
global MyFile
print "writing string to file "
for index in range(1000):
MyFile.write(testbuf)
pass
def strWithStringIO():
global MyStrIo
print "writing string to StrinIO "
for index in range(1000):
MyStrIo.write(testbuf)
def strWithStr():
global MyStr
print "Writing String to STR "
for index in range(500):
MyStr = MyStr + testbuf
def strWithCstr():
global MycStrIo
print "writing String to Cstring"
for index in range(1000):
MycStrIo.write(testbuf)
with Timer() as t:
strWithFiles()
print('##Request took %.03f sec.' % t.interval)
with Timer() as t:
strWithStringIO()
print('###Request took %.03f sec.' % t.interval)
with Timer() as t:
strWithCstr()
print('####Request took %.03f sec.' % t.interval)
with Timer() as t:
read1 = 'x' + MyFile.read(-1)
print('file read ##Request took %.03f sec.' % t.interval)
with Timer() as t:
read2 = 'x' + MyStrIo.read(-1)
print('stringIo read ###Request took %.03f sec.' % t.interval)
with Timer() as t:
read3 = 'x' + MycStrIo.read(-1)
print('CString read ####Request took %.03f sec.' % t.interval)
MyFile.close()
虽然 Python 文档站点说 cStringIO
比 StringIO
快,但结果表明 StringIO
在串联方面有更好的性能,为什么?
另一方面是,从 cStringIO
读取比 StringIO
更快(其行为类似于文件),因为我读取了 file 和 cStringIO
都在 C 中,那么为什么字符串连接很慢?
有没有其他方法可以比这些方法更快地处理字符串?
最佳答案
StringIO
表现更好的原因是在幕后,它只是保留了一个已写入的所有字符串的列表,并且只在必要时才组合它们。所以写操作就像将对象附加到列表一样简单。然而,cStringIO
模块没有这种奢侈,它必须将每个字符串的数据复制到它的缓冲区中,并在必要时调整其缓冲区的大小(这在写入大量字符串时会产生大量冗余的数据复制)数据)。
由于您正在编写大量较大的字符串,这意味着与 cStringIO
相比,StringIO
要做的工作更少。当从您写入的 StringIO
对象中读取时,它可以通过计算写入它的字符串的长度总和来优化所需的复制量,并预先分配该大小的缓冲区。
但是,StringIO
并不是连接一系列字符串的最快方法。这是因为它提供了额外的功能(寻找缓冲区的不同部分并在那里写入数据)。如果不需要此功能,您只需将列表字符串连接在一起,那么 str.join
是执行此操作的最快方法。
joined_string = "".join(testbuf for index in range(1000))
# or building the list of strings to join separately
strings = []
for i in range(1000):
strings.append(testbuf)
joined_string = "".join(strings)
关于Python cStringIO 在编写上比 StringIO 花费更多的时间(字符串方法的性能),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27010962/
我正在使用 python 的 csv.DictReader 但我正在用这样的字符串初始化它: dict_reader = csv.DictReader(StringIO.StringIO(some_s
我已经用谷歌搜索并在 SO 上搜索这些缓冲区模块之间的区别。不过,我还是不是很明白,我觉得我看的一些帖子已经过时了。 在 Python 2.7.11 中,我使用 r = requests.get(ur
在我的模型中,我想通过覆盖保存方法来格式化图像字段 我在我的模型中做到了这一点 from PIL import Image as Img from io import StringIO from dj
我正在使用 Boost 的序列化库序列化大量数据以通过网络发送。 Boost 的序列化库需要一个中间文件来进行序列化和反序列化。传输的数据量使得执行所有这些操作变得很尴尬。将事情保存在内存中会好得多。
StringIO 是我们在从文本中读取 Pandas 数据帧时使用的类似文件的字符串缓冲区对象,例如"How to create a Pandas DataFrame from a string?"
我在使用这两个类时得到了不同的结果。 In [15]: StringIO.StringIO().write(u'\u2222') In [16]: cStringIO.StringIO().write
所以,我关注了this question为了得到一些声音播放 Music21 ,这是代码: from music21 import * import random def main(): # Set
显然,我是 Python 的新手。 我想在下面的代码中使用 StringIO :提取 example.xml import os os.chdir('d:/py/xml/') from lxml i
我只是无法让 StreamHandler 与 StringIO 一起工作以接受来自进程的日志记录。奇怪的是,到 stdout 的流工作得很好。 这是我的代码: from time import sle
我们正在使用一些我们没有源代码的编译Python代码。该代码提示用户输入,我们正在尝试自动化该部分。 基本上要求输入用户名、密码,然后根据特定情况询问一些不同的问题。我不知道编译后的函数是使用raw_
我正在使用以下代码在线检索图像: import Image import urllib2 import cStringIO url = 'http://storage.googleapis.com/b
尝试[ see it running here ]: from sys import stdout, stderr from cStringIO import StringIO from loggin
我在使用 Ruby 的 StringIO 类时观察到一些非常奇怪的行为。 在 irb 控制台中输入以下内容: 2.3.0 :002 > original_string = 'test' => "te
如何在 StringIO 中用另一个字符串替换字符串? - 我听说如果它们的长度相同是可能的。 尝试: from cStringIO import StringIO c = 'can\nhaz\nfo
我似乎得到了不同的输出: from StringIO import * file = open('1.bmp', 'r') print file.read(), '\n' print StringIO
在 Python 中,我有一个文件流,我想将它的一部分复制到 StringIO 中。我希望它尽可能快,副本最少。 但如果我这样做: data = file.read(SIZE) stream = St
我正在寻找一些 StringIO -类似的类,它允许我从我的程序的不同部分同时写入和读取。 从程序的一部分我想将字符写入(追加)到缓冲区,从另一部分我想读取它们。 StringIO 的问题如下: bu
我有 python 3.6。我想从另一个名为“run.py”的 python 文件执行名为“operation.py”的 python 文件。 在 operation.py 中,我执行 from cS
我刚刚开始使用 Django 和 Python,正在尝试构建一个照片应用程序。该脚本正在生成缩略图,我想自己做。不幸的是我不明白 StringIO() 正在做什么。在这种情况下,Python 文档对我
我正在尝试使用将 rml 转换为 pdf, import cStringIO buf = cStringIO.StringIO() rml2pdf.go(rml, outputFileName=buf
我是一名优秀的程序员,十分优秀!