点击上方 "程序员小乐"关注, 星标或置顶一起成长
每天凌晨00点00分, 第一时间与你相约
每日英文
I wish you be happy, because it is my biggest wish. I'm also afraid you are happy, because then you will forget me.
我希望你幸福,因为那是我最大的心愿。我又怕你幸福,因为那样你就会忘了我。
每日掏心话
每个人都有觉得自己不够好,羡慕别人闪闪发光的时候,但其实大多人都是普通的。不要沮丧,不必惊慌,做努力爬的蜗牛或坚持飞的笨鸟,在最平凡的生活里,谦卑和努力。总有一天,你会站在最亮的地方,活成自己曾经渴望的模样。
来自:机器之心 | 责编:乐乐
t/5d31928c51882564c966a71c
程序员小乐(ID:study_tech)第 763 次推文 图片来自 Pexels
往日回顾:“公司要求提前复工,我辞职了”,这种情况该怎么办?(附上班后疫情防控权威指南)
正文
本文将介绍如何提升 Python 程序的效率,让它们运行飞快!
# 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 xslow_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!
欢迎在留言区留下你的观点,一起讨论提高。如果今天的文章让你有新的启发,学习能力的提升上有新的认识,欢迎转发分享给更多人。
欢迎各位读者加入程序员小乐技术群,在公众号后台回复“加群”或者“学习”即可。
猜你还想看
阿里、腾讯、百度、华为、京东最新面试题汇集
了解Linux的基础知识和一般概念
在 Spring Boot 中,如何干掉 if else!
Python2 已终结,入手Python 3,你需要这30个技巧
文章有问题?点此查看未经处理的缓存