公司动态

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

📅 2026/8/1 14:15:26
Python模块:内置模块time时间戳与性能计时
Python模块内置模块time时间戳与性能计时一、开篇time和datetime的分工time模块和datetime模块经常让人困惑——它们有重叠的功能。简单来说time模块更底层处理Unix时间戳、程序暂停、性能计时datetime模块更高级面向日期时间的创建、计算和格式化。⌨️ 快速区分importtimefromdatetimeimportdatetime# 获取现在的两种方式tstime.time()# time模块返回Unix时间戳浮点数dtdatetime.now()# datetime模块返回datetime对象print(ftime模块 → 时间戳:{ts})print(fdatetime模块 → datetime对象:{dt})# time模块的独特功能# - sleep() —— 暂停执行# - perf_counter() —— 高精度性能计时# - gmtime()/localtime() —— 结构化时间二、时间戳Unix纪元的秒数2.1 基本概念和操作importtime# Unix纪元1970年1月1日 00:00:00 UTC# 时间戳 从纪元到现在的秒数# 获取当前时间戳nowtime.time()print(f当前时间戳:{now})print(f类型:{type(now)})# class float# 纳秒级时间戳Python 3.7now_nstime.time_ns()print(f纳秒时间戳:{now_ns})# 时间戳转结构化时间localtime.localtime(now)utctime.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(fUTC时间:{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# 格式化时间nowtime.localtime()print(time.strftime(%Y-%m-%d %H:%M:%S,now))print(time.strftime(%A, %B %d, %Y,now))# 解析时间字符串time_str2024-06-15 14:30:00parsedtime.strptime(time_str,%Y-%m-%d %H:%M:%S)print(parsed)# struct_time# 转回时间戳tstime.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,width50):简单的进度条foriinrange(total1):percenti/total filledint(width*percent)bar█*filled░*(width-filled)print(f\r[{bar}]{percent*100:.0f}%,end,flushTrue)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# 测量代码执行时间starttime.perf_counter()# 模拟耗时操作resultsum(range(10_000_000))endtime.perf_counter()elapsedend-startprint(f执行时间:{elapsed:.4f}秒)# 创建计时器上下文管理器classTimer:上下文管理器——测量代码块执行时间def__enter__(self):self.starttime.perf_counter()returnselfdef__exit__(self,*args):self.endtime.perf_counter()self.elapsedself.end-self.startprint(f⏱ 耗时:{self.elapsed:.6f}秒)# 使用withTimer():total0foriinrange(1_000_000):totali**24.2 函数执行时间装饰器importtimefromfunctoolsimportwrapsdeftiming_decorator(func):测量函数执行时间的装饰器wraps(func)defwrapper(*args,**kwargs):starttime.perf_counter()resultfunc(*args,**kwargs)elapsedtime.perf_counter()-startprint(f⏱{func.__name__}执行耗时:{elapsed:.6f}秒)returnresultreturnwrappertiming_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 —— 包含sleepstarttime.perf_counter()time.sleep(1)perftime.perf_counter()-start# process_time —— 不包含sleepstarttime.process_time()time.sleep(1)proctime.process_time()-startprint(fperf_counter (含sleep):{perf:.2f}秒)print(fprocess_time (不含sleep):{proc:.4f}秒)compare_timers()# 使用建议# - 测量真实等待时间 → perf_counter()# - 测量CPU计算时间 → process_time()# - 测量代码优化效果 → perf_counter()考虑多次取平均4.4 性能对比工具importtimedefbenchmark(func,*args,runs100,**kwargs):简单的性能基准测试times[]for_inrange(runs):starttime.perf_counter()func(*args,**kwargs)times.append(time.perf_counter()-start)avgsum(times)/len(times)min_timemin(times)max_timemax(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):maplambdareturnlist(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()。记住这个分工。