import math
import time
import numpy as np
import torch
from d2l import torch as d2l

class Timer:  #@save
    """记录多次运行时间"""
    def __init__(self):
        self.times = []
        self.start()

    def start(self):
        """启动计时器"""
        self.tik = time.time()      # 获取当前时间的时间戳

    def stop(self):
        """停止计时器并将时间记录在列表中"""
        self.times.append(time.time() - self.tik)   # 将定时器启动到目前为止的时间差值存放到times列表中并返回该差值
        return self.times[-1]

    def avg(self):
        """返回平均时间"""
        return sum(self.times) / len(self.times)

    def sum(self):
        """返回时间总和"""
        return sum(self.times)

    def cumsum(self):
        """返回累计时间"""
        return np.array(self.times).cumsum().tolist()

n = 10000
a = torch.ones(n)       # a是含有10000个元素,每个元素都为1的张量
b = torch.ones(n)       # b是含有10000个元素,每个元素都为1的张量
c = torch.zeros(n)      # c是含有10000个元素,每个元素都为0的张量
timer = Timer()         # 启动计时器,记录当前时间的时间戳

# 执行10000次运算
for i in range(n):
    c[i] = a[i] + b[i]

# 两个向量相加,逐元素运算花费的时间
print(f'{timer.stop():.5f} sec')
# 输出:
# 0.13755 sec

# 两个向量相加,矢量化运算花费的时间
timer.start()
d = a + b
print(f'{timer.stop():.5f} sec')
# 输出:
# 0.00099 sec

 

posted on 2022-11-01 15:38  yc-limitless  阅读(23)  评论(0编辑  收藏  举报