程序来自http://wiki.woodpecker.org.cn/moin/MiscItems/2011-11-28


#!/usr/bin/python

import sys
import random
import time
import itertools
import operator
import collections

# 返回一个包含在指定范围内产生包含随机数的字典
def g(length, typerange):
    return [{'type':random.randint(0,typerange),'data':'hello%s' % x } for x in xrange(length)]

def f1(qrs):
   li=[]
   qrs.sort(key=operator.itemgetter('type'))
   for k,g in itertools.groupby(qrs,key=operator.itemgetter('type')):
       li.append({'type':k,'data':[i['data'] for i in g]})
   return li

def f2(qrs):
    d = collections.defaultdict(list)
    for q in qrs:
       d[q['type']].append(q['data'])
    result = [{'type': k, 'data': v} for k, v in d.items()]
    return result

def f3(qrs):
    new_list = {}
    for elem in qrs:
        new_list.setdefault(elem['type'], []).append(elem['data'])
    result = [{'type': k, 'data': v} for k, v in new_list.items()]
    return result

def t(f, a):
    start = time.time()
    f(a)
    end = time.time()
    return end - start

def main():
    l = 100000  #范围的上限
    tr = 10  #步长
    try:
       l = int(sys.argv[1])
    except:
       pass

    try:
       tr = int(sys.argv[2])
    except:
       pass

    print 'groupby     %s' % t(f1,g(l,tr))
    print 'defaultdict %s' % t(f2,g(l,tr))
    print 'setdefault  %s' % t(f3,g(l,tr))

if __name__ == '__main__':
    main()

函数t()用来计算f()的运行时间。t()的参数f是要执行的函数。

用到的几个模块和函数


Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐