我描述了一个使用第三方unicodecsv库的Python脚本。大部分时间都花在了_stringify function shown here上。有没有人对如何优化这个小循环有任何建议,或者这是否与你在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')