1

サードパーティの 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')
4

0 に答える 0