基于python代码实现500个节点进行多项式计算运行时间和所占内存然后将节点分区再次计算得出对比结果,并绘图
时间: 2024-02-20 22:02:20 浏览: 19
好的,相比于上一个问题,这个问题需要我们对比分区前后的运行时间和内存占用,并进行绘图展示。下面是实现代码:
```python
import numpy as np
import time
from memory_profiler import memory_usage
import matplotlib.pyplot as plt
# 生成500个随机系数的多项式
coeff = np.random.rand(500)
poly = np.poly1d(coeff)
# 计算分区前的运行时间和内存占用
start_time = time.time()
mem_usage = memory_usage((poly))
end_time = time.time()
run_time = end_time - start_time
mem_usage = max(mem_usage)
print("分区前:")
print("运行时间:{:.6f} 秒".format(run_time))
print("内存占用:{:.2f} MB".format(mem_usage))
# 将多项式分成两个部分并计算分区后的运行时间和内存占用
part1, part2 = np.split(poly, [250])
start_time = time.time()
mem_usage = memory_usage((part1, part2))
end_time = time.time()
run_time_part = end_time - start_time
mem_usage = max(mem_usage)
print("\n分区后:")
print("运行时间:{:.6f} 秒".format(run_time_part))
print("内存占用:{:.2f} MB".format(mem_usage))
# 计算分区前后的多项式结果并绘制图像
x = np.linspace(-10, 10, 1000)
y = poly(x)
y_part1 = part1(x)
y_part2 = part2(x)
plt.figure(figsize=(10, 5))
plt.subplot(1, 2, 1)
plt.plot(x, y, label='Original')
plt.plot(x, y_part1, label='Part 1')
plt.plot(x, y_part2, label='Part 2')
plt.legend()
plt.title('500个节点多项式分区前后对比')
plt.subplot(1, 2, 2)
plt.bar(['Original', 'Part'], [run_time, run_time_part])
plt.ylabel('运行时间(秒)')
plt.title('多项式计算运行时间对比')
plt.show()
```
在这段代码中,我们首先生成了一个包含500个随机系数的多项式,并计算出分区前的运行时间和内存占用。然后,我们将多项式分成两个部分,并计算出分区后的运行时间和内存占用。最后,我们绘制了分区前后的多项式结果对比图和运行时间对比图。
希望可以帮助到您!