我分析了一个使用 3rd 方 unicodecsv 库的 Python 脚本。大部分时间都花在了此处显示的 _stringify 函数上。有没有人对如何优化这个小循环有任何建议,或者这和你在 Python 中得到的一样好?我尝试了一些愚蠢的方法,包括抓取 mro() 元组并每次手动搜索它,但它甚至没有接近改进。
这是供参考的代码:
def _stringify(s, encoding, errors):
if s is None:
return ''
if isinstance(s, unicode):
return s.encode(encoding, errors)
elif isinstance(s, (int , float)):
pass #let csv.QUOTE_NONNUMERIC do its thing.
elif not isinstance(s, str):
s=str(s)
return s
这是引导您测试 unicodecsv 的内容。是的,我正在制作大约 3000-4000 列的 CSV。
import unicodecsv
import random
import StringIO
import cProfile
import datetime
# roughly the size of the data set I was working with
# still very big, a couple hundred megs of ram
data = []
for _ in xrange(5000):
row = []
for __ in xrange(4000):
row.append(random.randint(0,15000))
data.append(row)
fd = StringIO.StringIO()
writer = unicodecsv.writer(fd, encoding="utf-8")
p = cProfile.Profile()
n = datetime.datetime.utcnow()
p.enable()
for row in data:
writer.writerow(row)
p.disable()
print datetime.datetime.utcnow() - n, 'total time'
p.dump_stats('profile_output')