如果您只是操作二进制值序列,您会使用 numpy 吗?

发布于 2024-08-22 05:43:50 字数 65 浏览 4 评论 0原文

当您对二进制值列表进行大量操作时,使用 numpy 有什么优势吗?小范围内的整数怎么样(比如数字 1,2 和 3?)

Is there any advantage to using numpy when you're doing a large number of operations on lists of binary values? How about integers within a small range (like just the numbers 1,2, and 3?)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

柠北森屋 2024-08-29 05:43:50

消除循环是性能提升 (10 倍) 的来源:

import profile
import numpy as NP

def np_test(a2darray) :
  row_sums = NP.sum(a2darray, axis=1)
  return NP.sum(row_sums)

def stdlib_test2(a2dlist) :
  return sum([sum(row) for row in a2dlist])

A = NP.random.randint(1, 6, 1e7).reshape(1e4, 1e3)
B = NP.ndarray.tolist(A)

profile.run("np_test(A)")
profile.run("stdlib_test2(B)")

numpy

  • 0.025 CPU 中调用 10 个函数

列表

  • 0.280 CPU 中 10005 次函数调用

Eliminating the loops is the the source of the performance gain (10x):

import profile
import numpy as NP

def np_test(a2darray) :
  row_sums = NP.sum(a2darray, axis=1)
  return NP.sum(row_sums)

def stdlib_test2(a2dlist) :
  return sum([sum(row) for row in a2dlist])

A = NP.random.randint(1, 6, 1e7).reshape(1e4, 1e3)
B = NP.ndarray.tolist(A)

profile.run("np_test(A)")
profile.run("stdlib_test2(B)")

numpy:

  • 10 function calls in 0.025 CPU
    seconds

lists:

  • 10005 function calls in 0.280 CPU
    seconds
梦晓ヶ微光ヅ倾城 2024-08-29 05:43:50

如果输入值的数量很大,或者您正在进行大量操作,您可能需要尝试 位数组。或者,查看 Numpy 的 ndarray 中的 bool/int8/uint8 dtype:

In [1]: import numpy as np
In [2]: data = np.array([0,1,1,0], dtype=bool)
In [3]: data
Out[3]: array([False,  True,  True, False], dtype=bool)
In [4]: data.size
Out[4]: 4
In [5]: data.nbytes
Out[5]: 4

If the number of input values is huge, or if you are doing a lot of operations, you might want to try bitarray. Or, see the bool/int8/uint8 dtype in Numpy's ndarray:

In [1]: import numpy as np
In [2]: data = np.array([0,1,1,0], dtype=bool)
In [3]: data
Out[3]: array([False,  True,  True, False], dtype=bool)
In [4]: data.size
Out[4]: 4
In [5]: data.nbytes
Out[5]: 4
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文