学习笔记 —— python代码耗时及内存占用测试方法
创始人
2024-05-18 23:36:03
0

1、手写耗时测试

先看结果;
主要有三种方法,各自的时钟间隔如下:

  1. time.time()
    在这里插入图片描述

  2. timeit
    在这里插入图片描述

  3. time.time_ns() ( time is outputted in ns!).
    在这里插入图片描述

可见方法2,即timeit 的时钟间隔最短。

注:最后一个是以ns为单位的,前两个是以s为单位的

三种方法的时钟测量及调用方式如下:

import numpy as npimport time
from timeit import default_timer as timerdef checktick():M = 200timesfound = np.empty((M,))for i in range(M):# t1 = time.time()  # get timestamp from timer# t2 = time.time()  # get timestamp from timert1 = timer()  # get timestamp from timert2 = timer()  # get timestamp from timer# t1 = time.time_ns() # get timestamp from timer# t2 = time.time_ns()  # get timestamp from timerwhile (t2 - t1) < 1e-16:  # if zero then we are below clock granularity, retake timing# t2 = time.time()  # get timestamp from timert2 = timer() # get timestamp from timer# t2 = time.time_ns()  # get timestamp from timertimesfound[i] = t2  # record the time stamp# minDelta = 1000000Delta = np.diff(timesfound)  # it should be cast to int only when neededminDelta = Delta.min()return minDeltaif __name__ == "__main__":print(f"the Clock Granularity is {checktick()*10e8} nanosecond")# print(f"the Clock Granularity is {checktick()} nanosecond")

np.diff() 函数说明

import time
from functools import wraps# decorator to time
def timefn(fn):@wraps(fn)def measure_time(*args, **kwargs):t1 = time.time()result = fn(*args, **kwargs)t2 = time.time()print(f"@timefn: {fn.__name__} took {t2 - t1} seconds")return resultreturn measure_time@timefn
def calc_something(param1, param2):...add your code...if __name__ == "__main__":calc_something(param1=1000, param2=300)

2、开源工具

与手写相比,还有一些可以详细到每一个函数,甚至每一行代码的耗时的工具。(但会增大一些开销,仅测试使用)

2.1 耗时测试

cProfile

一般是内置的,不用装,直接运行

python -m cProfile -s cumulative JuliaSet.py

在这里插入图片描述

SnakeViz

安装

pip install snakeviz

运行

python -m cProfile -o profile.stats JuliaSet.py
python -m snakeviz profile.stats --server

在这里插入图片描述
在这里插入图片描述

line_profiler

安装

pip install line_profiler

使用

在函数上方添加 “@profile” 标识(这个时候编辑器可能会报错,不用管,反正咱们用的是命令行)
在这里插入图片描述
运行

python -m kernprof -l JuliaSet.py
python -m line_profiler JuliaSet.py.lprof

在这里插入图片描述

2.2 内存占用测试

测试内存的附加耗时比测试时间多的多,可能是10-100倍甚至更多。

memory_profiler

安装

pip install memory_profiler

使用

记得还是带上“@profile”
在这里插入图片描述
运行

python -m memory_profiler JuliaSet.py

在这里插入图片描述

mprof

mprof是memory_profiler内置的可视化工具

运行(这里需要matplotlib)

python -m mprof run JuliaSet.py
python -m mprof plot mprofile_20220116173811.dat

第二句的文件mprofile_20220116173811.dat与第一句的输出保持一致
在这里插入图片描述
在这里插入图片描述

2.3 CPU 占用 --psutil

psutil不止可以看CPU占用,也能看内存占用

pip install psutil

这个怎么用看官方示例吧, 还有文档

针对看CPU占用主要用这个函数:

psutil.cpu_percent(interval=1, percpu=True) 

可以看每个CPU核的占用百分比

相关内容

热门资讯

英语演讲稿:机会与挑战并存(... 英语演讲稿:机会与挑战并存 篇一Opportunities and Challenges Coexi...
有关现场改善的范文英语(优选... 有关现场改善的范文英语 篇一Title: The Importance of On-site Imp...
含哲理英语的句子【优选3篇】 含哲理英语的句子 篇一标题:人生的真正意义人生是一场旅程,不在于目的地,而在于沿途的风景。每个人都有...
低碳的英语作文(通用6篇) 低碳的英语作文 篇一The Importance of Low Carbon LifestyleIn...
介绍朋友的优点英语范文12篇... 篇一:我的好朋友李明的优点李明是我最好的朋友之一。他有许多优点,让我非常钦佩和喜欢。首先,李明非常聪...
新年英语作文 新年英语作文(精选5篇)  无论是在学校还是在社会中,许多人都写过作文吧,通过作文可以把我们那些零零...
中国轻纺城英语介绍范文(优选... 中国轻纺城英语介绍范文 篇一Title: Introduction to China Textile...
英语各式abcc押韵句子(优... 英语各式abcc押韵句子 篇一Loving the RainRaindrops falling on...
台风的英语作文(通用4篇) 台风的英语作文 篇一The Terrifying TyphoonTyphoon is a power...
代沟的作文(精彩5篇) 代沟的作文 篇一随着社会的不断发展和进步,代沟问题逐渐凸显出来。代沟是指不同年龄群体之间由于生活经历...
电子书的利弊英语作文【优质3... Article 1: The Pros and Cons of E-booksWith the ra...
话题英语作文【优选6篇】 话题英语作文 篇一:The Impact of Social Media on TeenagersW...
介绍自己英语作文【经典5篇】 Introducing Myself - Part OneHello, everyone! My n...
关于幽默感的英语句子【优选3... 关于幽默感的英语句子 篇一Humor is the best medicineHumor has t...
一封信英语作文(优选6篇) 一封信英语作文 篇一Dear Grandma,I hope this letter finds yo...
代沟的英语作文带翻译 有关代沟的英语作文带翻译(精选3篇)  在日常学习、工作和生活中,许多人都有过写作文的经历,对作文都...
新年计划英语作文(精简6篇) 新年计划英语作文 篇一My New Year's ResolutionsAs the new yea...
期盼元旦的英语作文【精彩3篇... Anticipating New Year's Day - Article OneNew Year'...
面试学校老师英语作文范文(推... 面试学校老师英语作文范文 篇一Title: The Importance of Communicat...
冬至英语作文(精选6篇) 冬至英语作文 篇一Winter SolsticeWinter Solstice, also know...