当前位置: 代码网 > it编程>前端脚本>Python > Pytorch精准记录函数运行时间的方法

Pytorch精准记录函数运行时间的方法

2024年11月12日 Python 我要评论
0. 引言参考pytorch官方文档对cuda的描述,gpu的运算是异步执行的。一般来说,异步计算的效果对于调用者来说是不可见的,因为每个设备按照排队的顺序执行操作pytorch对于cpu和gpu的同

0. 引言

参考pytorch官方文档对cuda的描述,gpu的运算是异步执行的。一般来说,异步计算的效果对于调用者来说是不可见的,因为

  • 每个设备按照排队的顺序执行操作
  • pytorch对于cpu和gpu的同步,gpu间的同步是自动执行的,不需要显示写在代码中

异步计算的后果是,没有同步的时间测量是不准确的。

1. 解决方案

参考引言中提到的帮助文档,pytorch官方给出的解决方案是使用torch.cuda.event记录时间,具体代码如下:

# import torch
start_event = torch.cuda.event(enable_timing=true)
end_event = torch.cuda.event(enable_timing=true)
start_event.record()

# run your code snippet here

end_event.record()
torch.cuda.synchronize()  # wait for the events to be recorded!
elapsed_time_ms = start_event.elapsed_time(end_event)  # elapsed time (ms)

将你的代码插入start_event.record()end_event.record()中间以测量时间(单位毫秒)。

有能力的读者也可以包装为装饰器或者with语句使用:

先书写一个自定义with类(contextmanager)

class cudatimer:
    def __init__(self):
        self.start_event = torch.cuda.event(enable_timing=true)
        self.end_event = torch.cuda.event(enable_timing=true)

    def __enter__(self):
        self.start_event.record()
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        self.end_event.record()
        torch.cuda.synchronize()
        self.elapsed_time = self.start_event.elapsed_time(self.end_event) / 1000 # ms -> s

再安装如下with语句返回:

with cudatimer() as timer:
	# run your code here
dt = timer.elapsed_time  # s

这样保证了多个文件调用时语句的简单性。特别提醒:获取timer.elapsed_time操作不要写在with语句内部。在with语句未结束时,是无法获取timer的成员变量的。

2. 补充

对于cpu和gpu混合操作的函数,使用torch.cuda.event可能会使统计时间比实际时间短,此时可以使用time.time()代替,标准的with对象书写如下:

# import time
class timer:
    def __enter__(self):
        self.start_time = time.time()
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        torch.cuda.synchronize()
        self.elapsed_time = time.time() - self.start_time

然后只需要将上文的with cudatimer() as timer替换为with timer() as timer即可。

到此这篇关于pytorch精准记录函数运行时间的方法的文章就介绍到这了,更多相关pytorch记录函数运行时间内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com