如何测量 python 代码每行所花费的 CPU 和 GPU 时间?



下面的代码计算整个python代码所花费的CPU时间。如何将其扩展到每行代码并添加 GPU 时间?

from timeit import default_timer as timer
start = timer()
# ...
end = timer()
print(end - start)

您可以通过以下方式跟踪 CPU 时间:

import time
time_collect = list()
start = time.process_time()
# single line code here    
time_collect.append(time.process_time() - start)
# next single code here    
time_collect.append(time.process_time() - start)
# next single code here    
time_collect.append(time.process_time() - start)
# This line will give you the time for every step after which you append the time
steps_time = [time_collect[i+1] - time_collect[i] for i in range(len(time_collect) - 1)]

如果您有GPU,则可能需要GPUtil才能从GPU获取状态,我没有挖掘他们的文档,但他们在README.md中提到了time库支持。