【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

相关推荐
金銀銅鐵33 分钟前
用 Python 实现 Take-Away 游戏
python·游戏
copyer_xyf1 小时前
Agent 流程编排
后端·python·agent
copyer_xyf2 小时前
Agent RAG
后端·python·agent
copyer_xyf2 小时前
【RAG】向量数据库:milvus
后端·python·agent
copyer_xyf2 小时前
Agent 记忆管理
后端·python·agent
星云穿梭17 小时前
用Python写一个带图形界面的学生管理系统——完整教程
python
金銀銅鐵17 小时前
用 Pygame 实现 15 puzzle
python·数学·游戏
黄忠1 天前
大模型之LangGraph技术体系
python·llm
hboot1 天前
AI工程师第二课 - 数据处理
人工智能·python·数据分析
用户8356290780512 天前
使用 Python 自动化 PowerPoint 形状布局与格式设置
后端·python