Python开发有时需要进行性能分析和性能优化。这时候需要记录一些比较耗时的函数执行时间问题,然后优化函数逻辑。python3中一般都有哪些方法。1.time.time()的使用方法比较简单,但是如果想更准确的计算函数的执行时间,会有精度损失,函数的耗时是没有办法统计的用很短的时间。importtimedeffunc():time.sleep(1)t=time.time()func()print(f'Time-consuming:{time.time()-t:.4f}s')耗时:1.0050s2,使用time.perf_counter()perf_counter是python3.3新增的,返回性能计数器的值,返回值为浮点型,统计结果包括睡眠时间,单个函数的返回值没有意义,只是多次操作取不同的结果才是有效的函数执行时间。importtimedeffunc():print('helloworld')t=time.perf_counter()func()print(f'time-consuming:{time.perf_counter()-t:.8f}s')helloworldtime-consuming:0.00051790s3,usetimeit.timeit()timeit()函数有5个参数:stmt参数是要执行的语句,默认是passsetup参数,用于执行初始化代码或者搭建环境语句,默认ispasstimer是计时Counter,默认是perf_counter()number是执行次数,默认是100万globals用于指定运行代码的命名空间,默认是None'helloworld')print(f'消耗时间:{timeit.timeit(stmt=func,number=1)}')helloworld耗时:0.00077059999999998244。使用装饰器来统计在实际的项目代码中,可以使用装饰器来方便地统计函数的运行时间。使用装饰器统计函数的执行时间的好处是对函数的侵入性小,易于编写和修改。用装饰器装饰函数的方案只适用于统计函数的运行时。如果需要统计代码块的耗时,则不能使用。在这种情况下,可以使用with语句来自动管理上下文。(1)同步函数统计importtimedefcoast_time(func):deffun(*args,**kwargs):t=time.perf_counter()result=func(*args,**kwargs)print(f'function:{func.__name__}耗时:{time.perf_counter()-t:.8f}s')returnresultreturnfun@coast_timedeftest():print('helloworld')if__name__=='__main__':test()(2)异步函数统计importasyncioimporttimefromasyncio.coroutinesimportiscoroutinefunctiondefcoast_time(func):deffun(*args,**kwargs):t=time.perf_counter()result=func(*args,**kwargs)print(f'function:{func.__name__}耗时:{time.perf_counter()-t:.8f}s')返回结果asyncdeffunc_async(*args,**kwargs):t=time.perf_counter()result=awaitfunc(*args,**kwargs)print(f'function:{func.__name__}耗时:{time.perf_counter()-t:.8f}s')返回结果ifiscoroutinefunction(func):返回func_asyncelse:返回fun@coast_timedeftest():print('hellotest')time.sleep(1)@coast_timeasyncdeftest_async():print('hellotest_async')awaitasyncio.sleep(1)if__name__=='__main__':test()asyncio.get_event_loop().run_until_complete(test_async())hello测试函数:test耗时:1.00230700shellotest_async函数:test_async耗时:1.00572550s5,带语句统计通过实现enter和exit函数,可以进入并退出上下文执行一些自定义的动作,比如连接或断开数据库、打开或关闭文件、记录开始或结束时间等,例如:我们用来统计功能块的执行时间。with语句不仅可以统计代码块的执行时间,还可以统计函数的执行时间,还可以统计多个函数执行时间的总和。与装饰器相比,它对代码的侵入性更大,不易修改。优点是使用起来比较灵活,不需要写太多重复的代码。importasyncioimporttimeclassCoastTime(object):def__init__(self):self.t=0def__enter__(self):self.t=time.perf_counter()返回selfdef__exit__(self,exc_type,exc_val,exc_tb):print(f'内存时:{time.perf_counter()-self.t:.8f}s')deftest():print('hellotest')withCoastTime():time.sleep(1)asyncdeftest_async():print('hellotest_async')withCoastTime():awaitasyncio.sleep(1)if__name__=='__main__':test()asyncio.get_event_loop().run_until_complete(test_async())hello测试时间:1.00723310shellotest_async缓存时间:1.00366820s
