当前位置: 首页 > news >正文

Python模块:内置模块time时间戳与性能计时

Python模块:内置模块time时间戳与性能计时

一、开篇:time和datetime的分工

time模块和datetime模块经常让人困惑——它们有重叠的功能。简单来说:time模块更底层,处理Unix时间戳、程序暂停、性能计时;datetime模块更高级,面向日期时间的创建、计算和格式化。

⌨️ 快速区分:

importtimefromdatetimeimportdatetime# 获取"现在"的两种方式ts=time.time()# time模块:返回Unix时间戳(浮点数)dt=datetime.now()# datetime模块:返回datetime对象print(f"time模块 → 时间戳:{ts}")print(f"datetime模块 → datetime对象:{dt}")# time模块的独特功能:# - sleep() —— 暂停执行# - perf_counter() —— 高精度性能计时# - gmtime()/localtime() —— 结构化时间

二、时间戳:Unix纪元的秒数

2.1 基本概念和操作

importtime# Unix纪元:1970年1月1日 00:00:00 UTC# 时间戳 = 从纪元到现在的秒数# 获取当前时间戳now=time.time()print(f"当前时间戳:{now}")print(f"类型:{type(now)}")# <class 'float'># 纳秒级时间戳(Python 3.7+)now_ns=time.time_ns()print(f"纳秒时间戳:{now_ns}")# 时间戳转结构化时间local=time.localtime(now)utc=time.gmtime(now)print(f"本地时间:{local.tm_year}-{local.tm_mon:02d}-{local.tm_mday:02d}"f"{local.tm_hour:02d}:{local.tm_min:02d}:{local.tm_sec:02d}")print(f"UTC时间:{utc.tm_year}-{utc.tm_mon:02d}-{utc.tm_mday:02d}"f"{utc.tm_hour:02d}:{utc.tm_min:02d}:{utc.tm_sec:02d}")# struct_time的属性forattrin['tm_year','tm_mon','tm_mday','tm_hour','tm_min','tm_sec','tm_wday','tm_yday','tm_isdst']:print(f"{attr}={getattr(local,attr)}")

2.2 人类可读的时间格式

importtime# ctime() —— 最快速的人类可读格式print(time.ctime())# Sat Jun 15 14:30:00 2024# 格式化时间now=time.localtime()print(time.strftime("%Y-%m-%d %H:%M:%S",now))print(time.strftime("%A, %B %d, %Y",now))# 解析时间字符串time_str="2024-06-15 14:30:00"parsed=time.strptime(time_str,"%Y-%m-%d %H:%M:%S")print(parsed)# struct_time# 转回时间戳ts=time.mktime(parsed)print(f"时间戳:{ts}")# 💡 strftime/strptime的格式代码和datetime模块一致

三、sleep():暂停执行

importtime# sleep(seconds) —— 暂停程序执行print("倒计时开始...")foriinrange(5,0,-1):print(i)time.sleep(1)# 暂停1秒print("时间到!")# 进度指示器defprogress_bar(total,width=50):"""简单的进度条"""foriinrange(total+1):percent=i/total filled=int(width*percent)bar="█"*filled+"░"*(width-filled)print(f"\r[{bar}]{percent*100:.0f}%",end="",flush=True)time.sleep(0.05)print()# progress_bar(100)# sleep()接受浮点数time.sleep(0.5)# 暂停500毫秒

四、性能计时:测量代码执行时间

4.1 perf_counter()——高精度计时

importtime# perf_counter() —— 高精度性能计数器# 包含sleep时间,适合测量墙钟时间(Wall-clock time)# 测量代码执行时间start=time.perf_counter()# 模拟耗时操作result=sum(range(10_000_000))end=time.perf_counter()elapsed=end-startprint(f"执行时间:{elapsed:.4f}秒")# 创建计时器上下文管理器classTimer:"""上下文管理器——测量代码块执行时间"""def__enter__(self):self.start=time.perf_counter()returnselfdef__exit__(self,*args):self.end=time.perf_counter()self.elapsed=self.end-self.startprint(f"⏱ 耗时:{self.elapsed:.6f}秒")# 使用withTimer():total=0foriinrange(1_000_000):total+=i**2

4.2 函数执行时间装饰器

importtimefromfunctoolsimportwrapsdeftiming_decorator(func):"""测量函数执行时间的装饰器"""@wraps(func)defwrapper(*args,**kwargs):start=time.perf_counter()result=func(*args,**kwargs)elapsed=time.perf_counter()-startprint(f"⏱{func.__name__}执行耗时:{elapsed:.6f}秒")returnresultreturnwrapper@timing_decoratordefslow_calculation(n):"""模拟慢计算"""returnsum(i**2foriinrange(n))@timing_decoratordeffast_calculation(n):"""使用数学公式的快速计算"""returnn*(n-1)*(2*n-1)//6slow_calculation(1_000_000)fast_calculation(1_000_000)

4.3 process_time()——CPU时间

importtime# process_time() —— 进程使用的CPU时间# 不包含sleep时间,适合测量纯计算性能defcompare_timers():"""对比perf_counter和process_time"""# perf_counter —— 包含sleepstart=time.perf_counter()time.sleep(1)perf=time.perf_counter()-start# process_time —— 不包含sleepstart=time.process_time()time.sleep(1)proc=time.process_time()-startprint(f"perf_counter (含sleep):{perf:.2f}秒")print(f"process_time (不含sleep):{proc:.4f}秒")compare_timers()# 💡 使用建议:# - 测量真实等待时间 → perf_counter()# - 测量CPU计算时间 → process_time()# - 测量代码优化效果 → perf_counter()(考虑多次取平均)

4.4 性能对比工具

importtimedefbenchmark(func,*args,runs=100,**kwargs):"""简单的性能基准测试"""times=[]for_inrange(runs):start=time.perf_counter()func(*args,**kwargs)times.append(time.perf_counter()-start)avg=sum(times)/len(times)min_time=min(times)max_time=max(times)print(f"{func.__name__}: 平均={avg*1000:.3f}ms, "f"最小={min_time*1000:.3f}ms, 最大={max_time*1000:.3f}ms "f"(运行{runs}次)")# 对比两种实现defmethod_1(n):"""列表推导式"""return[x**2forxinrange(n)]defmethod_2(n):"""map+lambda"""returnlist(map(lambdax:x**2,range(n)))benchmark(method_1,100000)benchmark(method_2,100000)

五、总结

time模块和datetime模块各司其职。time管底层的时间戳、暂停和性能计时;datetime管高级的日期时间操作。

💡核心要点:

功能函数说明
获取时间戳time.time()Unix秒数
暂停time.sleep(s)暂停s秒
性能计时time.perf_counter()高精度墙钟时间
CPU时间time.process_time()进程CPU时间
结构化时间time.localtime()struct_time

性能测试用perf_counter(),日期操作交给datetime,暂停用sleep()。记住这个分工。

http://www.jsqmd.com/news/1307404/

相关文章:

  • 金华 B2B 工厂 AI 长效获客:检索金华 GEO 优化 AI 推广公司,本土技术服务商维艺网络凭自研全域技术领跑浙中工业数字营销赛道 - 行业分析师
  • 佛山眼镜店连锁怎么选?2026年本地配镜机构服务观察与实用指南 - 优质品牌商家
  • 聚龙汇刘睿指导学员落地长期盈利项目
  • ESP32-S3-LCD-1.85开发板全解析:从硬件拆解到LVGL智能终端实战
  • gdb断点调试python代码
  • 浠水县居民搬家公司推荐、公司搬迁公司哪家好?2026避坑指南:4个坑+5条硬标准,帮你绕开90%的坑 - geo88
  • 为什么Unity/Unreal实时渲染中AI纹理突然出现闪烁接缝?——基于GPU管线深度逆向的6步诊断法(含Shader IR日志解析脚本)
  • 恒温器项目实战:从PID算法到嵌入式系统设计的完整指南
  • 2026东阳医院搬迁公司推荐,健身器材搬运公司哪家好?乔恒公司推荐 - geo88
  • 【SD面部修复节点终极指南】:20年CV工程师亲授5大避坑法则与3步提效实战法
  • 2024十大论文降重工具实测与学科适配方案
  • 改简历改吐了,我干脆自己做了个工具
  • ESP32-S3触摸屏开发实战:从硬件选型到LVGL图形界面开发
  • 阿里云盘Refresh Token终极获取指南:三步扫码解锁云盘自动化能力
  • AI模型边缘部署失败率高达63%?揭秘5类硬件适配陷阱及3步零误差落地流程
  • idea application.yaml 文件中的 Ctrl+Click 无法跳转
  • 深度解析:League Akari 1.5.0的Electron模块化架构演进与性能优化实践
  • Pico-8游戏画面驱动8段数码管:嵌入式图形处理与硬件交互实践
  • 看板状态自动标注准确率<68%?你缺的不是AI,而是这1套经CNCF项目验证的看板意图识别协议(含开源SDK)
  • GO Markets:从执行效率切入的维度归纳
  • ESP32-S3-LCD-2.8B开发板全解析:从硬件集成到LVGL图形界面实战
  • ESP32-S3驱动1.85寸触摸屏全攻略:从硬件解析到LVGL界面开发
  • 这款英语背单词APP,正在帮培训机构解决最头疼的三大难题
  • 基于ESP32与MQTT的边缘AI图像识别结果实时上报方案
  • AI辅助游戏脚本开发:图像识别自动读取人物血量实战
  • 2026安徽省合肥公办免学费!安徽建工技师学院怎么联系?怎么报名? - 最新资讯
  • 13.3英寸HDMI显示屏硬件解析与多平台适配实战指南
  • 呼叫中心“移动坐席”能力实测:谁真能做到“一部手机搞定客服”?
  • 2026年全国选购通讯继电器优质厂家推荐参考 - 奔跑123
  • RookieAI_yolov8:5分钟开启你的AI瞄准助手,告别手动瞄准烦恼!