import timeit
import torch
import numpy as np
# 创建一个形状为 (1000, 5) 的随机张量
c = torch.randint(10, (1000, 5))
a = c.shape[0]
b = c.shape[1]
k = 2
# Python 列表版本
def list_version():
w1 = [1/c.shape[0]] * c.shape[0]
w2 = [1/c.shape[1]] * c.shape[1]
w1 = [x*k for x in w1]
return w1, w2
# NumPy 数组版本
def numpy_version():
w3 = np.full(c.shape[0], 1/c.shape[0])
w4 = np.full(c.shape[1], 1/c.shape[1])
w3 = w3 * k
return w3, w4
# 测试两种方法的执行时间
list_time = timeit.timeit(list_version, number=1000)
numpy_time = timeit.timeit(numpy_version, number=1000)
print(f'List version time: {list_time}')
print(f'NumPy version time: {numpy_time}')
List version time: 0.060718438937328756
NumPy version time: 0.006332025048322976