# slow_program.pyfrom decimal import *def exp(x): getcontext().prec += 2 i, lasts, s, fact, num = 0, 0, 1, 1, 1 while s != lasts: lasts = s i += 1 fact *= i num *= x s += num / fact getcontext().prec -= 2 return +sexp(Decimal(150))exp(Decimal(400))exp(Decimal(3000))复制代码
~ $ time python3.8 slow_program.pyreal 0m11,058suser 0m11,050ssys 0m0,008s复制代码
~ $ python3.8 -m cProfile -s time slow_program.py 1297 function calls (1272 primitive calls) in 11.081 seconds Ordered by: internal time ncalls tottime percall cumtime percall filename:lineno(function) 3 11.079 3.693 11.079 3.693 slow_program.py:4(exp) 1 0.000 0.000 0.002 0.002 {built-in method _imp.create_dynamic} 4/1 0.000 0.000 11.081 11.081 {built-in method builtins.exec} 6 0.000 0.000 0.000 0.000 {built-in method __new__ of type object at 0x9d12c0} 6 0.000 0.000 0.000 0.000 abc.py:132(__new__) 23 0.000 0.000 0.000 0.000 _weakrefset.py:36(__init__) 245 0.000 0.000 0.000 0.000 {built-in method builtins.getattr} 2 0.000 0.000 0.000 0.000 {built-in method marshal.loads} 10 0.000 0.000 0.000 0.000 <frozen importlib._bootstrap_external>:1233(find_spec) 8/4 0.000 0.000 0.000 0.000 abc.py:196(__subclasscheck__) 15 0.000 0.000 0.000 0.000 {built-in method posix.stat} 6 0.000 0.000 0.000 0.000 {built-in method builtins.__build_class__} 1 0.000 0.000 0.000 0.000 __init__.py:357(namedtuple) 48 0.000 0.000 0.000 0.000 <frozen importlib._bootstrap_external>:57(_path_join) 48 0.000 0.000 0.000 0.000 <frozen importlib._bootstrap_external>:59(<listcomp>) 1 0.000 0.000 11.081 11.081 slow_program.py:1(<module>)...复制代码
def timeit_wrapper(func): @wraps(func) def wrapper(*args, **kwargs): start = time.perf_counter() # Alternatively, you can use time.process_time() func_return_val = func(*args, **kwargs) end = time.perf_counter() print('{0:<10}.{1:<8} : {2:<8}'.format(func.__module__, func.__name__, end - start)) return func_return_val return wrapper复制代码
@timeit_wrapperdef exp(x): ... print('{0:<10} {1:<8} {2:^8}'.format('module', 'function', 'time'))exp(Decimal(150))exp(Decimal(400))exp(Decimal(3000))复制代码
~ $ python3.8 slow_program.pymodule function time __main__ .exp : 0.003267502994276583__main__ .exp : 0.038535295985639095__main__ .exp : 11.728486061969306复制代码
import functoolsimport time# caching up to 12 different results@functools.lru_cache(maxsize=12)def slow_func(x): time.sleep(2) # Simulate long computation return x slow_func(1) # ... waiting for 2 sec before getting resultslow_func(1) # already cached - result returned instantaneously!slow_func(3) # ... waiting for 2 sec before getting result复制代码
七、使用局部变量
# Example #1class FastClass: def do_stuff(self): temp = self.value # this speeds up lookup in loop for i in range(10000): ... # Do something with `temp` here# Example #2import randomdef fast_function(): r = random.random for i in range(10000): print(r()) # calling `r()` here, is faster than global random.random() 复制代码
def main(): ... # All your previously global codemain()复制代码
# Slow:import redef slow_func(): for i in range(10000): re.findall(regex, line) # Slow!# Fast:from re import findalldef fast_func(): for i in range(10000): findall(regex, line) # Faster!复制代码
f'{s} {t}' # Fast!s + ' ' + t ' '.join((s, t))'%s %s' % (s, t) '{} {}'.format(s, t)Template('$s $t').substitute(s=s, t=t) # Slow!复制代码
原文链接:
https://towardsdatascience.com/making-python-programs-blazingly-fast-c1cd79bd1b32
(*本文为AI科技大本营翻译文章,转载请微信联系 1092722531)
◆精彩推荐◆
1、评选进行中,参与投票即有机会参与抽奖,60+公开课免费学习
如果群满100人,无法自动进入,可添加会议小助手微信:婷婷,151 0101 4297(电话同微信)