【Python】(自定义类)计算语句执行时间

一个玩具,写着来玩的。

用的time模块,代码很简单(所以才说是个玩具)


代码:

python 复制代码
import time
class TimeStamp:
	__timestamp=None
	__key=None
	def __init__(self,tips=None,key=None):
		self.__timestamp={}
		self.NewStamp(tips,key)
	def NewStamp(self,tips,key=None):
		self.__timestamp[key]=(time.time(),tips)
		self.__key=key
	def Duration(self,key=None,printVal=True):
		if(key not in self.__timestamp):
			key=self.__key
		val=round(time.time()-self.__timestamp[key][0],2)
		if(printVal):
			print(f'{self.__timestamp[key][1]}:  {val}s')
		return val

测试样例+运行结果:

python 复制代码
import random
if __name__=='__main__':
	ts=TimeStamp('总用时','Total')

	ts.NewStamp('创建列表')
	lst=[random.randint(1,100) for i in range(1000000)]
	ts.Duration()

	ts.NewStamp('列表复制')
	lst=lst*100
	ts.Duration()

	ts.NewStamp('字串化')
	s=str(lst)
	ts.Duration()

	ts.NewStamp('哈希计算')
	h=hash(s)
	ts.Duration()

	ts.Duration('Total')

小小声
  1. 这么简单的东西都上传?是来互联网灌垃圾的是吧(没错
  2. 没想到hash的效率挺高,反倒是变量的字串化有可能成为瓶颈(只不过也得数据量大到相当程度才会影响效率

未经本人同意不得私自转载,本文发布于CSDN:https://blog.csdn.net/weixin_44733774/article/details/134609775

相关推荐
zone773910 小时前
001:简单 RAG 入门
后端·python·面试
F_Quant10 小时前
🚀 Python打包踩坑指南:彻底解决 Nuitka --onefile 配置文件丢失与重启报错问题
python·操作系统
允许部分打工人先富起来11 小时前
在node项目中执行python脚本
前端·python·node.js
IVEN_11 小时前
Python OpenCV: RGB三色识别的最佳工程实践
python·opencv
haosend12 小时前
AI时代,传统网络运维人员的转型指南
python·数据网络·网络自动化
曲幽12 小时前
不止于JWT:用FastAPI的Depends实现细粒度权限控制
python·fastapi·web·jwt·rbac·permission·depends·abac
IVEN_1 天前
只会Python皮毛?深入理解这几点,轻松进阶全栈开发
python·全栈
Ray Liang1 天前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
AI攻城狮1 天前
如何给 AI Agent 做"断舍离":OpenClaw Session 自动清理实践
python
千寻girling1 天前
一份不可多得的 《 Python 》语言教程
人工智能·后端·python