以下是根据《流畅的python》修改部分代码:
#!/usr/bin/env python
# encoding: utf-8
import timeit
import random
import string
TIMES = 10000
def random_char(y):
return ''.join(random.choice(string.ascii_letters) for x in range(y))
SETUP = """
import random
import string
def random_char(y):
return ''.join(random.choice(string.ascii_letters) for x in range(y))
symbols = random_char(10000)
def non_ascii(c):
return c > 127
"""
# SETUP = random_char(10)
def clock(label, cmd):
res = timeit.repeat(cmd, setup=SETUP, number=TIMES)
print(label, *('{:.3f}'.format(x) for x in res))
clock('listcomp :', '[ord(s) for s in symbols if ord(s) > 127]')
clock('listcomp + func :', '[ord(s) for s in symbols if non_ascii(ord(s))]')
clock('filter + lambda :', 'list(filter(lambda c: c > 127, map(ord, symbols)))')
clock('filter + func :', 'list(filter(non_ascii, map(ord, symbols)))')
结果如下:
listcomp : 8.093 8.029 7.942
listcomp + func : 16.419 16.220 16.152
filter + lambda : 12.938 12.886 12.998
filter + func : 13.401 13.535 13.091
#!/usr/bin/env python
# encoding: utf-8
"""
@version: 0.1
@author: aszhou
@license: Apache Licence
@contact: zjmjordan@sina.com
@site:
@software: PyCharm
@file: demo.py
@time: 2017/7/18 0018 15:49
@description:
"""
import timeit
import random
import string
TIMES = 10000
def random_char(y):
return ''.join(random.choice(string.ascii_letters) for x in range(y))
bs = [s for s in random_char(100)]
SETUP = """
import random
import string
def random_char(y):
return ''.join(random.choice(string.ascii_letters) for x in range(y))
symbols = random_char(100)
varas = [s for s in symbols]
varbs = [s for s in symbols]
def func(va,vb):
l=[]
for m in varas:
for n in varbs:
l.append((m,n))
"""
# SETUP = random_char(10)
def clock(label, cmd):
res = timeit.repeat(cmd, setup=SETUP, number=TIMES)
print(label, *('{:.3f}'.format(x) for x in res))
clock('listcomp :', '[(a,b) for a in varas for b in varbs]')
clock('listcomp + func :', 'func(varas,varbs)')
结果如下
listcomp : 7.159 6.899 6.908
listcomp + func : 11.767 11.623 11.395
我的运行环境python 3.6,在使用内置函数时(不准确,需要更多内部函数进行测试),列表推导速度最快,但是当使用自定义函数时,反而性能最差。