【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

相关推荐
Ralph_Y1 分钟前
C++:迭代器失效
开发语言·c++
站大爷IP1 分钟前
Python操作Redis:高效缓存设计与实战
python
smart margin3 分钟前
Python安装教程
开发语言·python
Looooking4 分钟前
Python 流程自动化之 DrissionPage 使用示例
python·自动化·drissionpage
阿贵---4 分钟前
定时任务专家:Python Schedule库使用指南
jvm·数据库·python
TsukasaNZ4 分钟前
如何为开源Python项目做贡献?
jvm·数据库·python
云晓-7 分钟前
从零入门智能体:核心概念与发展脉络全解析
python
weixin_3077791311 分钟前
OpenClaw-CN 安全增强方案:从理念到落地的全面剖析
开发语言·人工智能·算法·安全·语言模型
nananaij13 分钟前
【LeetCode-05 好数对的数目 python解法】
python·算法·leetcode
new code Boy15 分钟前
前端核心基础汇总
开发语言·javascript·原型模式