龙空技术网

一招实现让Python Numpy快到飞起!

不秃头程序员 458

前言:

现在你们对“python动态链接库和numpy哪个快”都比较关怀,我们都想要分析一些“python动态链接库和numpy哪个快”的相关资讯。那么小编也在网络上收集了一些关于“python动态链接库和numpy哪个快””的相关内容,希望大家能喜欢,小伙伴们一起来了解一下吧!

在本文中,笔者将介绍Numexpr这个强大的Python库,它可以显著提升NumPy数组的计算性能。

Numexpr是一个专门用于提高NumPy数组计算性能的工具。它通过避免为中间结果分配内存,提高了缓存利用率并减少了内存访问,从而实现更好的性能。相比于NumPy,Numexpr的多线程功能可以充分利用所有核心,通常带来显著的性能扩展。

github链接:

Numpy计算

当Numpy遇到大数组时,逐元素计算会遇到两个极端。例如下面的代码是两个大的NumPy数组:

import numpy as npimport numexpr as nex = np.random.rand(10_000_000)y = np.random.rand(10_000_000)

如若要计算表达式 x ** 8 + y * 2 的结果,通常有两种方法:

一是Numpy的向量化计算,使用两个临时数组temp_x和temp_y分别存储 x ** 8 和 y * 2 的结果。实现方案如下:

import numpy as npimport numexpr as neimport timeitx = np.random.rand(100_000_000)y = np.random.rand(100_000_000)def calculation():    temp_x = x ** 8    temp_y = y * 2    result = temp_x + temp_y    print(result)execution_time = timeit.timeit(calculation, number=1)print(f"Execution time: {execution_time} seconds")

这时候,内存中有四个数组,分别是:x、y、temp_x 和 temp_y,势必容易造成大量的内存浪费。

Execution time: 3.1453814 seconds

并且,每个数组的大小都超出了CPU缓存的容量,无法很好的利用它。

另一种方法是遍历两个数组中每个元素并分别计算:

import numpy as npimport numexpr as neimport timeitx = np.random.rand(100_000_000)y = np.random.rand(100_000_000)z = np.empty(100_000_000, dtype=np.uint32)def calcu_elements(x, y, z):    for i in range(0, len(x), 1):        z[i] = x[i] ** 8 + 2 * y[i]# 使用lambda函数将calcu_elements函数包装起来,并将其作为参数传递给timeit.timeit函数execution_time = timeit.timeit(lambda: calcu_elements(x, y, z), number=1)print(f"Execution time: {execution_time} seconds")
Execution time: 57.0129075 seconds

这种方法的性能更差,运算速度非常慢,因为它不能使用矢量化计算,并且只能部分利用CPU缓存。

Numexpr计算

Numexpr提供了一个evaluate方法,它接收一个表达式字符串,并将其编译为字节码进行计算。

同时,Numexpr还包含一个虚拟机程序,其中包含多个向量寄存器,用于存储数据块,每个向量寄存器使用的块大小为4096。

在计算过程中,Numexpr会将数据块发送到CPU的L1缓存中,以避免内存访问的延迟,并提高计算效率。此外,Numexpr的虚拟机是用C编写的,不受Python的GIL限制,可以充分利用多核CPU的计算能力。

相比单独使用NumPy,Numexpr在计算大型数组时通常会更快。实现代码如下:

import numpy as npimport numexpr as neimport timeitx = np.random.rand(100_000_000)y = np.random.rand(100_000_000)def calculate_expression():    return ne.evaluate('x ** 8 + y * 2')execution_time = timeit.timeit(calculate_expression, number=1)print(f"Execution time: {execution_time} seconds")
Execution time: 0.36257230000000007 seconds

由此可以看出,Numexpr计算速度相比于Numpy,明显快到飞起!

标签: #python动态链接库和numpy哪个快