python统计秒数

code

1.没有cuda的版本

import time

s = time.time()
for i in range(100):
	pass
t = time.time()
print("time:{} sec".format(t-s))

2.cuda 同步

torch.cuda.synchronize()
start = time.time()
result = model(input)
torch.cuda.synchronize()
end = time.time()

ref

https://blog.youkuaiyun.com/qq_36268040/article/details/100085263

### 统计 Python 代码运行时间的方法 在 Python 中,有多种方式可以用来测量代码的执行时间。以下是几种常见且有效的方式: #### 使用 `time` 模块 这是最基础也是最常见的方法之一。通过记录起始时间和结束时间并计算差值即可得到代码片段的执行耗时。 ```python import time start_time = time.time() # 记录开始时刻 # 被测代码段 end_time = time.time() # 记录结束时刻 execution_duration = end_time - start_time print(f"Code executed in {execution_duration} seconds.") [^2] ``` 这种方法简单易懂,适合快速测试短小脚本或函数的性能开销。 #### 自定义装饰器实现更灵活的时间度量功能 为了提高可重用性和减少冗余代码量,我们还可以构建一个通用性的装饰器来包裹待评估的目标函数。 ```python def timer_decorator(func): def wrapper(*args, **kwargs): before_calling = time.perf_counter() result_of_function = func(*args,**kwargs) after_calling = time.perf_counter() duration_spent = after_calling-before_calling print("%s completed within %.6fs."%(func.__name__,duration_spent)) return result_of_function return wrapper @timer_decorator def sample_task(n_iterations=1e7): total_sum = sum(range(int(n_iterations))) return total_sum sample_task(5e6) ``` 上述例子展示了如何创建自定义定时器装饰器,并将其应用于任意需要监控效率的任务之上[^1]。 #### 高精度计时工具——`timeit`模块 当追求极致精确度的时候,则推荐选用标准库里的`timeit`组件来进行微基准测试工作。相比手动调用两次timestamp而言,它能更好地屏蔽掉外部干扰因素的影响,提供更加可靠的统计数据支持决策制定过程。 ```python from timeit import default_timer as dtimer setup_code=""" import math """ test_stmt="math.sqrt(i) for i in range(100)" elapsed=(dtimer()-dtimer())*1E9 # nanoseconds level resolution print("%.3f ns per loop"%elapsed) alternatively, import timeit res=timeit.repeat(stmt=test_stmt , setup=setup_code,number=10000,repeats=5) avg=min(res)/len(res)*1E9; std=max(res)-min(res) print("Average:%.3f ±%.3f ns"%(avg,std)) [^3] ``` 以上介绍了三种主流途径去量化分析一段特定逻辑所需耗费的实际秒数或者纳秒数量级差异情况下的表现状况。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值