python - 为什么 Numpy 操作 0.1M 矩阵 1000 次比操作 1M 矩阵 100 次要快得多?
问题描述
我发现了一个奇怪的现象,即 Numpy 在操作较小的矩阵时似乎要快得多,即使在数据总量相同的情况下也是如此。为什么会这样?
import time
import numpy as np
def a():
ts = time.time()
for i in range(100):
x = np.random.rand(100000, 2).reshape(-1, 2)
y = np.random.rand(100000)
te = time.time()
print(te - ts)
def b():
ts = time.time()
for i in range(1000):
x = np.random.rand(10000, 2).reshape(-1, 2)
y = np.random.rand(10000)
te = time.time()
print(te - ts)
a()
b()
a()
0.30100059509277344
0.25199460983276367
0.30100131034851074
解决方案
如果您不使用该time
库,它们大致相同 - 这是有道理的。计算函数时间的变化是巨大的。只有一次不会验证一个函数是否更快(如果它没有明显更快)。
def a():
for i in range(100):
x = np.random.rand(100000, 2).reshape(-1, 2)
y = np.random.rand(100000)
def b():
for i in range(1000):
x = np.random.rand(10000, 2).reshape(-1, 2)
y = np.random.rand(10000)
%%timeit -n100 -r10
a()
225 ms ± 4.78 ms per loop (mean ± std. dev. of 10 runs, 100 loops each)
%%timeit -n100 -r10
b()
224 ms ± 2.86 ms per loop (mean ± std. dev. of 10 runs, 100 loops each)
推荐阅读
- mysql - 如何在 MySQL 查询中选择查询某个值?
- react-native - 如何使 BottomTabBar 上的图标扩展 BottomTabBar
- html - Blazor 应用程序中的 EditForm 有多个提交按钮
- reactjs - Axios NTLM 不适用于 POST(但适用于 GET)
- python - Celery/Django 工作人员检测何时没有工作
- java - 局部变量背后的想法是最终的,但在使用内部类时外部类字段不是
- javascript - 如何让 span 元素完全覆盖按钮?
- javascript - 如何通过登录 React Admin 来实现额外的自定义对话框(基于服务器响应)?
- postgresql - Postgresql对中等大表的简单查询非常慢
- flutter - 如何在 Dart 中为条件导入设置自定义属性?