首页 > 编程语言 >Python: 对程序做性能分析及计时统计

Python: 对程序做性能分析及计时统计

时间:2022-11-27 17:34:36浏览次数:66  
标签:Python self 计时 程序 start func time def 0.000

1.对整个程序的性能分析

如果只是想简单地对整个程序做计算统计,通常使用UNIX下的time命令就足够了。

(base) ➜  Learn-Python time python someprogram.py       
python someprogram.py  0.10s user 0.01s system 98% cpu 0.117 total

由于我用的是Mac系统,和Linux系统的输出可能有不同,不过关键都是这三个时间:

  • user: 运行用户态代码所花费的时间,也即CPU实际用于执行该进程的时间,其他进程和进程阻塞的时间不计入此数字。

  • system: 在内核中执行系统调用(如I/O调用)所花费的CPU时间。

  • total(Linux下应该是real):即挂钟时间(wall-clock time),也称响应时间(response time)、消逝时间(elapsed time),是进程运行开始到结束所有经过的时间,包括了进程使用的时间片和进程阻塞的时间(例如等待I/O完成)。

请注意,若user + system > total,可能存在多个处理器并行工作;
若user + system < total,则可能在等待磁盘、网络或其它设备的响应。

也就说上面这个程序的挂钟时间为0.251s,CPU实际用于执行该进程的时间为0.24s,用于系统调用的时间为0.01s。

再来看看另外一个极端,如果想针对程序的行为产生一份详细的报告,那么可以使用cProfile模块:

(base) ➜  Learn-Python python -m cProfile someprogram.py
         7 function calls in 0.071 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.002    0.002    0.071    0.071 someprogram.py:1(<module>)
        1    0.039    0.039    0.068    0.068 someprogram.py:1(func1)
        1    0.029    0.029    0.029    0.029 someprogram.py:3(<listcomp>)
        1    0.000    0.000    0.001    0.001 someprogram.py:7(func2)
        1    0.000    0.000    0.000    0.000 someprogram.py:9(<listcomp>)
        1    0.000    0.000    0.071    0.071 {built-in method builtins.exec}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

可见我们上述代码的热点是在于func1函数。

这里再多说几句,这里传入的-m -cProfile可选参数意为将Python的cPofile模块做为脚本运行,实际上等价于:

python /Users/orion-orion/miniforge3/lib/python3.9/cProfile.py someprogram.py

当然,中间那个路径取决于大家各自的环境。这也就是说我们将some_program.py做为cProfile.py程序的输入参数,目的就是对其进行性能分析。

2.对特定代码段做性能分析

2.1 分析函数和语句块

不过对于做代码性能分析而言,更常见的情况则处于上述两个极端情况之间。

比如,我们可能已经知道了代码把大部分运行时间都花在几个某几个函数上了。要对函数进行性能分析,使用装饰器就能办到。示例如下:

import time
from functools import wraps

def timethis(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        start = time.perf_counter()
        r = func(*args, **kwargs)
        end = time.perf_counter()
        print("{}.{} : {}".format(func.__module__, func.__name__, end - start))
        return r
    
    return wrapper

要使用这个装饰器,只要简单地将其放在函数定义之前,就能得到对应函数的计时信息了。示例如下:

@timethis
def countdown(n):
    while n > 0:
        n -= 1

countdown(10000000)       

控制台打印输出:

__main__.countdown : 0.574160792

请注意,在进行性能统计时,任何得到的结果都是近似值。我们这里使用的函数time.perf_counter()是能够提供给定平台上精度最高的计时器,它返回一个秒级的时间值。但是,它计算的仍然是挂钟时间(墙上时间),这会受到许多不同因素的影响(例如机器当前的负载),且它会将程序等待中断的sleep(休眠)时间也计算在内。

如果相对于挂钟时间,我们更感兴趣的是进程时间(包括在内核态和用户态中所花费的CPU时间),那么可以使用time.process_time()来替代。示例如下:

def timethis(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        start = time.process_time()
        r = func(*args, **kwargs)
        end = time.process_time()
        print("{}.{} : {}".format(func.__module__, func.__name__, end - start))
        return r
    
    return wrapper

接下来我们看如何对语句块进行计算统计,这可以通过定义一个上下文管理器来实现。示例如下:

from contextlib import contextmanager

@contextmanager
def timeblock(label):
    start = time.perf_counter()
    try:
        yield
    finally:
        end = time.perf_counter()
        print("{} : {}". format(label, end - start))

下面这个例子演示了这个上下文管理器是如何工作的:

with timeblock("counting"):
    n = 10000000
    while n > 0:
        n -= 1

控制台打印输出如下所示:

counting : 0.7888195419999999

最后,我们来看一种一劳永逸的方案:在time模块中的函数之上构建一个更高层的接口来模拟秒表,从而解决对函数、对代码块的计时问题。

import time

class Timer:
    def __init__(self, func=time.perf_counter):
        self.elapsed = 0.0
        self._func = func
        self._start = None
    
    def start(self):
        if self._start is not None:
            raise RuntimeError("Already started!")
        self._start = self._func()
    
    def stop(self):
        if self._start is None:
            raise RuntimeError("Not started!")
        end = self._func()
        self.elapsed += end - self._start
        self._start = None
    
    def reset(self):
        self.elapsed = 0.0
    
    @property
    def running(self):
        return self._start is not None

    def __enter__(self):
        self.start()
        return self
    
    def __exit__(self, *args):
        self.stop()

这个类定义了一个定时器,可以根据用户的需要启动、停止和重置它。Timer类将总的花费时间记录在elapsed属性中。下面的实例展示了如何使用这个类:

t = Timer()

# Use 1: Explicit start/stop
t.start()
countdown(1000000)
t.stop()
print(t.elapsed)
# 0.058305625

# Use 2: As a context manager
with t:
    countdown(1000000)
print(t.elapsed)
# 0.11482683300000004

with Timer() as t2:
    countdown(1000000)
print(t2.elapsed)
# 0.056095916999999995

如同前面所展示的,由Timer类记录的时间是挂钟时间,其中包含了所有的sleeping时间。如果仅想获取进程的CPU时间(包括在用户态和内核态中的时间),可以用time.process_time()取代。示例如下:

t = Timer(time.process_time)
with t:
    countdown(1000000)
print(t.elapsed)
# 0.05993699999999999

2.2 分析单条代码片段

如果要对短小的代码片段做性能统计,timeit模块会很有帮助。示例如下:

from timeit import timeit

print(timeit("math.sqrt(2)", "import math"))
# 0.07840395799999997

print(timeit("sqrt(2)", "from math import sqrt"))
# 0.05943025000000002

timeit会执行第一个参数中指定的语句一百万次,然后计算时间。第二个参数是一个配置字符串,在运行测试之前会先执行以设定好环境。如果要修改需要迭代的次数,只需要提供一个number参数即可:

print(timeit("math.sqrt(2)", "import math", number=10000000))
# 0.7569702089999999

print(timeit("sqrt(2)", "from math import sqrt", number=10000000))
# 0.5865757500000002

最后但同样重要的是,如果打算进行详细的计时统计分析,请确保先阅读timetimeit以及其他相关模块的文档。这样才能理解不同系统平台之间的重要差异以及其他一些缺陷。

参考

标签:Python,self,计时,程序,start,func,time,def,0.000
From: https://www.cnblogs.com/orion-orion/p/16930169.html

相关文章

  • 微信小程序国密算法实现库sm-crypto
    sm-crypto简介摘要:该算法不公开,调用该算法时,需要通过加密芯片的接口进行调用。为非对称加密,基于。无线局域网标准的分组数据算法。对称加密,密钥长度和分组长度均为位。可......
  • 2022-2023-1 20221415 《计算机基础与程序设计》第十二周学习总结
    2022-2023-120221415《计算机基础与程序设计》第十二周学习总结作业信息这个作业属于哪个课程<班级的链接>(2022-2023-1-计算机基础与程序设计)这个作业要求在......
  • 为什么我做数据库类的程序要用代码生成器,而且是前前后后,反反复复 [转]...
    前几篇文章提到改善工作效率的工具,这此工具对我们日常开发或多或少的有些改善。有网友对代码生成器感兴趣,有些工具还会可能会改变你开发数据库软件的思路和模式,这里我也来......
  • 小程序登录
    https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/user-login/code2Session.htmlhttps://developers.weixin.qq.com/apiExplorer?apiName=addMessageTemplat......
  • Basler的python库安装(windows)
    Basler官方的python支持放到了GitHub上,GitHub-basler/pypylon:TheofficialpythonwrapperforthepylonCameraSoftwareSuite截止到2022.11.27日,支持到python3.1......
  • WordPress程序备受喜爱的原因:十八般武艺
    众所周知,WordPress是个功能强大且颇受欢迎的开源博客平台。WordPress友好的界面和操作的简便性为它带来了无数用户,WordPress甚至可以被作为内容发布系统(CMS)来使用。当你尝试......
  • Python time sleep()方法
    描述Pythontimesleep(secs)函数推迟调用线程的运行,可通过参数secs指秒数,表示进程挂起的时间。语法sleep()方法语法:time.sleep(t)参数t--推迟执行的秒数。返回......
  • Python 打开和读取文件的方式
    这是一篇介绍python读取文件的几种方式文章一、打开和读取文件的方式"""打开文件的方式可以使用f=open(path,'r')f.close()来打开和关闭文件或者使用withopen(fi......
  • Python安装(Windows)
    个人喜欢从官网直接下载具体版本安装,然后通过cmd的pip安装其他包。1、官网下载Python,PythonReleasesforWindows|Python.org2、安装选择允许添加路径到系统环境,选择......
  • 2022-2023-1 20221320 《计算机基础与程序设计》第十三周学习总结
    学期(2022-2023-1)学号(20221320)《计算机基础与程序设计》第十二周学习总结作业信息各项要求具体内容<班级的链接>2022-2023-1-计算机基础与程序设计<作业要......