抄写下面的程序,并比较两种不同矩阵运算方式的速度: import numpy as np import time my_arr = np.arange(1000000) my_list = list(range(1000000)) beginTime = time.perf_counter() for _ in range(10): my_arr2 = my_arr * 2 tNp = time.perf_counter() -beginTime beginTime = time.perf_counter() for _ in range(10): my_list2 = [x * 2 for x in my_list] tList = time.perf_counter() -beginTime print("tNp = ", tNp) print("tList = ", tList)
时间: 2023-12-30 12:04:38 浏览: 140
numpy-1.22.4+vanilla-cp311-cp311-win-amd64-whl
代码如下:
```python
import numpy as np
import time
my_arr = np.arange(1000000)
my_list = list(range(1000000))
beginTime = time.perf_counter()
for _ in range(10):
my_arr2 = my_arr * 2
tNp = time.perf_counter() - beginTime
beginTime = time.perf_counter()
for _ in range(10):
my_list2 = [x * 2 for x in my_list]
tList = time.perf_counter() - beginTime
print("tNp = ", tNp)
print("tList = ", tList)
```
这段代码分别使用了 NumPy 库和 Python 自带的列表来对一个长度为 1000000 的数组进行矩阵运算,比较两种运算方式的速度。其中,重要的是 `time.perf_counter()` 函数,它返回一个 CPU 时间,以秒为单位。
程序的运行结果可能略有不同,但一般来说,NumPy 库的速度要远远快于 Python 自带的列表。
阅读全文