让你的Python运行更快

 讨厌Python的人总是说,他们不想使用它的原因之一是它很  。嗯,特定程序(无论使用何种编程语言)是快还是慢,在很大程度上取决于编写该程序的开发人员以及编写优化  而  快速的  程序的技能和能力  。

因此,让我们证明一些人是错误的,让我们看看如何改善Python  程序的性能  并使它们真正更快!

时序分析

 
在开始进行任何优化之前,我们首先需要找出代码的哪些部分实际上会使整个程序变慢。有时程序的瓶颈可能很明显,但是如果您不知道它在哪里,那么这里有一些可供您选择的选项:

# slow_program.py
from 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 +s


exp(Decimal(150))
exp(Decimal(400))
exp(Decimal(3000))

最懒惰的“配置文件”

 
首先,最简单和诚实的说是非常懒惰的解决方案-Unix  time 命令:

~ $ time python3.8 slow_program.py


real  0m11,058s
user  0m11,050s
sys   0m0,008s

如果您只想计时整个程序,这可能会起作用,通常这是不够的……

最详细的分析

 
另一端是  cProfile,它将为您提供  过多  信息:

~ $ 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>)
...

在这里,我们使用cProfile 模块和  time 参数运行测试脚本  ,以便按内部时间(cumtime)对行进行排序  。这给了我们  很多  信息,您在上面看到的行大约是实际输出的10%。由此可见,  exp 函数是罪魁祸首(  Surprise,Surprise),现在我们可以更详细地了解时序和性能分析...

时序特定功能

 
现在我们知道了将注意力转移到哪里,我们可能想对慢速函数计时,而不用测量其余的代码。为此,我们可以使用简单的装饰器:

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_wrapper
def 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.py
module     function   time  
__main__  .exp      : 0.003267502994276583
__main__  .exp      : 0.038535295985639095
__main__  .exp      : 11.728486061969306

有一点要考虑的是  什么样的  时间,我们其实(想)措施。时间包提供  time.perf_counter 和  time.process_time。此处的区别是perf_counter返回绝对值,其中包括Python程序进程未运行时的时间,因此它可能会受到计算机负载的影响。另一方面,process_time仅返回用户时间(不包括系统时间),这仅是您的处理时间。

使其更快

 
现在是有趣的部分。让我们让您的Python程序运行得更快。我(大部分)不会向您展示一些可以神奇地解决您的性能问题的技巧,技巧和代码段。这更多地是关于一般构想和策略的,这些构想和策略在使用时可能会对性能产生巨大影响,在某些情况下,最高可以提高30%。

使用内置数据类型

 
这个很明显。内置数据类型非常快,特别是与树或链接列表之类的自定义类型相比。这主要是因为内置程序是用C实现的  ,因此在使用Python进行编码时我们的速度实在无法与之匹敌。

使用lru_cache缓存/记忆

 

import functools
import 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 result
slow_func(1)  # already cached - result returned instantaneously!


slow_func(3)  # ... waiting for 2 sec before getting result

使用局部变量

 
这与在每个作用域中查找变量的速度有关。我正在编写  每个作用域,因为它不只是使用局部变量还是全局变量。实际上,即使在函数(最快),类级属性(例如self.name ,较慢)和全局变量(例如,最慢)等全局  变量之间,查找速度实际上也有所不同  time.time 。

您可以通过使用看似不必要(直接无用的)的分配来提高性能,如下所示:

#  Example #1
class 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 #2
import random


def fast_function():
    r = random.random
    for i in range(10000):
        print(r())  # calling `r()` here, is faster than global random.random()

使用函数

 
这似乎违反直觉,因为调用函数会将更多的东西放到堆栈上,并从函数返回中产生开销,但这与上一点有关。如果仅将整个代码放在一个文件中而不将其放入函数中,则由于全局变量,它的运行速度会慢得多。因此,您可以通过将整个代码包装在main 函数中并调用一次来加速代码  ,如下所示:

def main():
    ...  # All your previously global code


main()

不访问属性

 
可能会使程序变慢的另一件事是  点运算符  (.),在访问对象属性时使用。该运算符使用触发字典查找  __getattribute__,这会在代码中产生额外的开销。那么,我们如何才能真正避免(限制)使用它呢?

#  Slow:
import re


def slow_func():
    for i in range(10000):
        re.findall(regex, line)  # Slow!


#  Fast:
from re import findall


def fast_func():
    for i in range(10000):
        findall(regex, line)  # Faster!

当心字符串

 
当使用模数  (%s)或  .format()。进行循环运行时,字符串操作可能会变得非常慢  。我们有什么更好的选择?我们唯一应该使用的是  f-string,它是最易读,简洁且最快的方法。因此,根据该推文,这是您可以使用的方法列表-最快到最慢:

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!

生成器本质上并没有更快,因为它们被允许进行惰性计算,从而节省了内存而不是时间。但是,保存的内存可能会导致您的程序实际运行得更快。怎么样?好吧,如果您有一个很大的数据集,并且没有使用生成器(迭代器),那么数据可能会溢出CPU  L1缓存,这将大大减慢内存中值的查找。

就性能而言,非常重要的一点是CPU可以将正在处理的所有数据尽可能地保存在缓存中。

 

结论

 
优化的首要规则是  不这样做。但是,如果确实需要,那么我希望这些技巧可以帮助您。但是,在优化代码时要小心,因为它可能最终使您的代码难以阅读,因此难以维护,这可能会超出优化的好处。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值