专栏名称: OFweek人工智能
提供人工智能行业最新热点新闻、技术、产品以及线上线下研讨会、产品资讯、市场信息等。
目录
相关文章推荐
清华经管学院职业发展中心  ·  活动 | BUILD YOUR ... ·  2 天前  
人力葵花  ·  各岗位薪资等级表(2.0).xls ·  2 天前  
人力资源法律  ·  工作纠纷与领导互殴被打骨折算工伤吗?| ... ·  2 天前  
人力葵花  ·  入职、在职、离职风险排查.xls ·  3 天前  
51好读  ›  专栏  ›  OFweek人工智能

这些方法,能够让你的Python程序快如闪电

OFweek人工智能  · 公众号  ·  · 2020-05-12 19:59

正文





选自towardsdatascience

作者: Martin Heinz
机器之心编译
参与:郭元晨、魔王
本文将介绍如何提升 Python 程序的效率,让它们运行飞快!


讨厌 Python 的人总是会说,他们不想用 Python 的一个重要原因是 Python 很慢。而事实上,无论使用什么编程语言,特定程序的运行速度很大程度上取决于编写程序的开发人员以及他们优化程序、加快程序运行速度的技能。

那么,让我们证明那些人错了!本文将介绍如何提升 Python 程序的效率,让它们运行飞快!


计时与性能分析

在开始优化之前,我们首先需要找到代码的哪一部分真正拖慢了整个程序。有时程序性能的瓶颈显而易见,但当你不知道瓶颈在何处时,这里有一些帮助找到性能瓶颈的办法:

注:下列程序用作演示目的,该程序计算 e 的 X 次方(摘自 Python 文档):

# slow_program.py
from decimal import *

def exp(x):
    getcontext().prec += 2
    i, lasts, s, fact, num = 00111
    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 :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 :57(_path_join)
       48    0.000    0.000    0.000    0.000 :59()
        1    0.000    0.000   11.081   11.081 slow_program.py:1()
...

这里,我们结合 cProfile 模块和 time 参数运行测试脚本,使输出行按照内部时间(cumtime)排序。这给我们提供了大量信息,上面你看到的行只是实际输出的 10%。从输出结果我们可以看到 exp 函数是罪魁祸首(惊不惊喜,意不意外),现在我们可以更加专注于计时和性能分析了……

计时专用函数

现在我们知道了需要关注哪里,那么我们可能只想要给运行缓慢的函数计时而不去管代码的其他部分。我们可以使用一个简单的装饰器来做到这点:

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 库提供了 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

上面的函数使用 time.sleep 模拟了繁重的计算过程。当我们第一次使用参数 1 调用函数时,它等待了 2 秒钟后返回了结果。当再次调用时,结果已经被缓存起来,所以它跳过了函数体,直接返回结果。

使用局部变量

这和每个作用域中变量的查找速度有关。我之所以说「每个作用域」,是因为这不仅仅关乎局部变量或全局变量。事实上,就连函数中的局部变量、类级别的属性和全局导入函数这三者的查找速度都会有区别。函数中的局部变量最快,类级别属性(如 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






请到「今天看啥」查看全文