python - python中的嵌套循环比平面快吗?
问题描述
在一个相关问题中,有人想知道为什么以一种方式嵌套两个周期(更长更短)另一种更快(更短更长)。
现在我遇到了一个比嵌套慢的扁平循环。怎么会这样?
from time import perf_counter as clock
import matplotlib.pyplot as plt
def long_short():
start = clock()
counter = 0
for i in range(100):
for j in range(10):
counter += 1
return (clock() - start)*1e6
def short_long():
start = clock()
counter = 0
for i in range(10):
for j in range(100):
counter += 1
return (clock() - start)*1e6
def single():
start = clock()
counter = 0
for i in range(1000):
counter += 1
return (clock() - start)*1e6
y1, y2, y3 = [], [], []
for i in range(30):
y1.append(long_short())
y2.append(short_long())
y3.append(single())
plt.figure()
ax1 = plt.plot(y1, c="b", label="Longer loop over shorter")
ax2 = plt.plot(y2, c="g", label="Shorter loop over longer")
ax3 = plt.plot(y3, c="r", label="Single loop")
plt.xlabel("n", fontsize=16)
plt.ylabel("Time (us)", fontsize=16)
plt.legend(loc=2, fontsize=14)
plt.show()
解决方案
推荐阅读
- php - PHP从纯文本Javascript中提取信息
- javascript - 如何在 ReactJS 中渲染通过 props 的对象?
- ios - 根据值(360)或百分比(100%)创建彩色圆圈
- nginx - 将 NGINX 配置为仅允许一个唯一的 ip 每天执行 5 个 POST 请求
- matlab - 从 CSV 文件 Matlab 中读取特定列的数字数据?
- dojo - 如何在dojo Modaldialog中单击关闭按钮时捕获事件?
- android - reddit 移动应用如何在发送新消息时自动更新回收站?[包括 GIF]
- java - 为 ACTION_SHOW 传递两个数据模式意图
- python - 如何将类型提示添加到我的猴子修补函数到现有模块的类?
- react-native - 用于反应原生静态图像并引发警告的 Jest 快照