wordpress网站支持中文注册,爱站seo排名可以做哪些网站,广东十大排名建筑公司,网站做交互设计0. 引言
参考Pytorch官方文档对CUDA的描述#xff0c;GPU的运算是异步执行的。一般来说#xff0c;异步计算的效果对于调用者来说是不可见的#xff0c;因为
每个设备按照排队的顺序执行操作Pytorch对于CPU和GPU的同步#xff0c;GPU间的同步是自动执行的#xff0c;不需…0. 引言
参考Pytorch官方文档对CUDA的描述GPU的运算是异步执行的。一般来说异步计算的效果对于调用者来说是不可见的因为
每个设备按照排队的顺序执行操作Pytorch对于CPU和GPU的同步GPU间的同步是自动执行的不需要显示写在代码中
异步计算的后果是没有同步的时间测量是不准确的。
1. 解决方案
参考引言中提到的帮助文档Pytorch官方给出的解决方案是使用torch.cuda.Event记录时间具体代码如下
start_event torch.cuda.Event(enable_timingTrue)
end_event torch.cuda.Event(enable_timingTrue)
start_event.record()# Run your code snippet hereend_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()中间以测量时间单位毫秒。本人亲测使用time.time()函数得到的函数运行时间为105ms而使用该方法得到的运行时间为19ms
有能力的读者也可以包装为装饰器或者with语句使用
先书写一个自定义with类ContextManager
class CudaTimer:def __init__(self):self.start_event torch.cuda.Event(enable_timingTrue)self.end_event torch.cuda.Event(enable_timingTrue)def __enter__(self):self.start_event.record()return selfdef __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的成员变量的。