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()。记住这个分工。