leaf-perfmon 1.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 LeafProfiler
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,449 @@
1
+ Metadata-Version: 2.4
2
+ Name: leaf_perfmon
3
+ Version: 1.0.0
4
+ Summary: Lightweight, extensible Python performance profiler with minimal overhead
5
+ Author-email: FourWater <FourWaterLeaf@163.com>
6
+ License: MIT
7
+ Keywords: profiler,performance,monitoring,memory,cpu,io,lock,gc
8
+ Classifier: Development Status :: 4 - Beta
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.7
13
+ Classifier: Programming Language :: Python :: 3.8
14
+ Classifier: Programming Language :: Python :: 3.9
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
19
+ Classifier: Topic :: System :: Monitoring
20
+ Requires-Python: >=3.7
21
+ Description-Content-Type: text/markdown
22
+ License-File: LICENSE
23
+ Provides-Extra: psutil
24
+ Requires-Dist: psutil>=5.0.0; extra == "psutil"
25
+ Provides-Extra: requests
26
+ Requires-Dist: requests>=2.20.0; extra == "requests"
27
+ Provides-Extra: full
28
+ Requires-Dist: perfmon[psutil,requests]; extra == "full"
29
+ Dynamic: license-file
30
+
31
+ # leaf_perfmon — Python 性能检测库
32
+ https://img.shields.io/badge/python-3.7+-blue.svg
33
+
34
+ https://img.shields.io/pypi/v/perfmon.svg
35
+
36
+ https://img.shields.io/badge/License-MIT-yellow.svg
37
+
38
+ https://img.shields.io/badge/code%2520style-black-000000.svg
39
+
40
+ perfmon 是一个轻量、高性能、可扩展的 Python 性能检测库,提供函数级、代码块级乃至文件级的性能剖析。
41
+ 它不仅测量执行时间、内存占用、CPU 时间,还支持 I/O 等待时间、锁竞争、异常统计、GC 暂停、HTTP 请求详情、缓存命中率 等高级指标。
42
+ 通过灵活的采样、阈值过滤、轻量模式,perfmon 能在生产环境中以极低的开销运行。
43
+
44
+ ## ✨ 核心特性
45
+ ### 多粒度检测:
46
+
47
+ 装饰器(函数/方法)、上下文管理器(任意代码块)、文件级执行。
48
+
49
+ ### 全面指标:
50
+
51
+ ### 基础:
52
+
53
+ 耗时、CPU 时间、内存分配(增量 & 峰值)、调用次数。
54
+
55
+ ### 扩展:
56
+
57
+ 文件读写 I/O、锁等待(threading/asyncio)、异常类型统计、GC 暂停、HTTP 请求(requests)、缓存命中率。
58
+
59
+ ### 资源(需 psutil):
60
+
61
+ CPU 使用率、进程内存 RSS。
62
+
63
+ ### 低开销设计:
64
+
65
+ 全局开关(零开销短路)
66
+
67
+ 采样统计(按比例跳过检测)
68
+
69
+ 轻量模式(不记录 min/max/avg)
70
+
71
+ 慢调用阈值(只记录耗时超限的调用)
72
+
73
+ ### 调用树追踪:
74
+
75
+ 自动记录父子调用关系,直观呈现函数调用图。
76
+
77
+ ### 异步/生成器友好:
78
+
79
+ 完整支持 async def 和生成器函数。
80
+
81
+ ### 导出功能:
82
+
83
+ JSON / CSV 格式导出,便于二次分析或可视化。
84
+
85
+ ### 零依赖核心:
86
+
87
+ 仅需 Python 标准库(扩展指标需相应库时可选)。
88
+
89
+ ## 📦 安装
90
+ bash
91
+ ````
92
+ pip install perfmon
93
+ ````
94
+ 可选依赖(用于部分扩展指标):
95
+
96
+ bash
97
+ ````
98
+ pip install perfmon[psutil] # 资源监控(CPU 利用率、内存 RSS)
99
+ pip install perfmon[requests] # HTTP 请求监控
100
+ pip install perfmon[full] # 安装所有扩展
101
+ ````
102
+ ## 🚀 快速入门
103
+ 1️⃣ 检测函数
104
+ python
105
+ ````
106
+ import perfmon as pm
107
+ import time
108
+
109
+ @pm.profile(memory=True, cpu=True)
110
+ def slow_function():
111
+ time.sleep(0.1)
112
+ return sum(range(10**6))
113
+
114
+ slow_function()
115
+ pm.report() # 打印性能统计表格
116
+ ````
117
+ 输出示例:
118
+
119
+ text
120
+ ````
121
+ 名称 调用 总时(s) 平均(s) 最小(s) 最大(s) 总CPU(s) 平均CPU 最小CPU 最大CPU 内存(B) 峰值(B) CPU%
122
+ ----------------------------------------------------------------------------------------------------------------------------------
123
+ slow_function 1 0.10123 0.10123 0.10123 0.10123 0.02001 0.02001 0.02001 0.02001 2048 8192 12.5
124
+ ````
125
+ 2️⃣ 检测代码块
126
+ python
127
+ ````
128
+ with pm.profile_context("数据加载", memory=True):
129
+ data = [i**2 for i in range(100000)]
130
+ ````
131
+ 3️⃣ 检测整个脚本
132
+ python
133
+ ````
134
+ pm.profile_file("my_script.py", measure_time=True, memory=True)
135
+ pm.report()
136
+ ````
137
+ 4️⃣ 导出 JSON 报告
138
+ python
139
+ ````
140
+ pm.export_json("perf_results.json")
141
+ ````
142
+ ## 📚 详细使用指南
143
+ ### 🔹 装饰器 @profile
144
+ python
145
+ ````
146
+ @pm.profile(
147
+ name=None, # 自定义显示名称(默认函数限定名)
148
+ measure_time=True, # 测量耗时
149
+ memory=False, # 测量内存分配(需 tracemalloc)
150
+ cpu=False, # 测量 CPU 时间
151
+ lite_mode=None, # 局部轻量模式(覆盖全局)
152
+ sample_rate=None, # 局部采样率(覆盖全局)
153
+ slow_threshold=None # 局部慢调用阈值(覆盖全局)
154
+ )
155
+ ````
156
+ 支持:普通函数、异步函数、生成器函数。
157
+
158
+ 自动记录:调用次数、耗时(若开启)、CPU 时间(若开启)、内存增量/峰值(若开启)、异常类型(若全局配置 monitor_exceptions=True)。
159
+
160
+ ### 🔹 缓存命中率装饰器 @profile_cache
161
+ python
162
+ ````
163
+ @pm.profile_cache(maxsize=128)
164
+ def expensive_func(n):
165
+ # 计算结果并缓存
166
+ return n * n
167
+ ````
168
+ 自动统计缓存命中/未命中次数。
169
+
170
+ 需通过 pm.configure(monitor_cache=True) 启用记录到 perfmon 统计中。
171
+
172
+ ### 🔹 上下文管理器 profile_context
173
+ python
174
+ ````
175
+ with pm.profile_context(
176
+ name, # 代码块名称
177
+ measure_time=True,
178
+ memory=False,
179
+ cpu=False
180
+ ):
181
+ # 你的代码块
182
+ ````
183
+ 同样支持异步上下文管理器(async with)。
184
+
185
+
186
+ ### 🔹 文件级检测 profile_file
187
+ python
188
+ ````
189
+ pm.profile_file(filename, measure_time=True, memory=False, cpu=False)
190
+ ````
191
+ 执行指定 Python 文件,并将其整体作为一个检测项(名称为 file:文件名)。
192
+
193
+ ### 🔹 全局配置 configure
194
+ python
195
+ ````
196
+ pm.configure(
197
+ # 基本设置
198
+ lite_mode=False, # 轻量模式(不记录 min/max/avg)
199
+ sample_rate=1.0, # 采样率 0.0~1.0
200
+ slow_threshold=0.0, # 慢调用阈值(秒)
201
+ record_parent=True, # 记录调用者(调用树)
202
+ record_children=True, # 记录子调用(调用树)
203
+ resource_monitor=False, # 启用资源监控(需 psutil)
204
+
205
+ # 扩展指标开关(默认 False)
206
+ monitor_io=False, # 文件 I/O 等待时间
207
+ monitor_locks=False, # 锁等待时间
208
+ monitor_exceptions=False, # 异常类型统计
209
+ monitor_gc=False, # GC 暂停时间
210
+ monitor_http=False, # HTTP 请求详情(需 requests)
211
+ monitor_cache=False # 缓存命中率(配合 @profile_cache)
212
+ )
213
+ ````
214
+ 所有开关均可动态修改,且修改后立即生效。
215
+
216
+ ### 🔹 控制开关
217
+ python
218
+ ````
219
+ pm.enable() # 全局启用检测(默认)
220
+ pm.disable() # 全局禁用检测(零开销)
221
+ pm.reset() # 清空所有已收集的统计信息
222
+ ````
223
+ ### 🔹 报告与导出
224
+ python
225
+ ````
226
+ pm.report(sort_by='total_time') # 打印统计表格,可按任意列排序
227
+
228
+ pm.export_json("path/to/file.json") # 导出全部指标为 JSON
229
+ pm.export_csv("path/to/file.csv") # 导出主要指标为 CSV
230
+ ````
231
+ ### 📊 检测指标详解
232
+ 指标分类 指标名称 说明 启用方式
233
+
234
+ 基础 调用次数 函数/代码块被执行次数 始终记录
235
+
236
+ 总耗时 / 平均 / 最小 / 最大 墙钟时间(秒) measure_time=True
237
+
238
+ CPU 时间 进程 CPU 时间(秒) cpu=True
239
+
240
+ 内存增量 执行期间内存分配净增量(字节) memory=True
241
+
242
+ 内存峰值 执行期间内存分配峰值(字节) memory=True
243
+
244
+ 扩展 I/O 读耗时 文件读操作累计耗时(秒) configure(monitor_io=True)
245
+
246
+ I/O 写耗时 文件写操作累计耗时(秒) 同上
247
+
248
+ 锁等待时间 threading.Lock / asyncio.Lock 获取等待时间 configure(monitor_locks=True)
249
+
250
+ 异常统计 被检测函数抛出的异常类型及次数 configure(monitor_exceptions=True)
251
+
252
+ GC 暂停时间 垃圾回收器执行耗时(累计) configure(monitor_gc=True)
253
+
254
+ HTTP 请求 每个 URL 的请求次数、总耗时、状态码分布(需 requests) configure(monitor_http=True)
255
+
256
+ 缓存命中率 被 @profile_cache 装饰的函数命中/未命中次数 configure(monitor_cache=True)
257
+
258
+ 资源 CPU 利用率 执行期间平均 CPU 使用率(%),需 psutil 且 resource_monitor=True resource_monitor=True
259
+
260
+ 进程内存 RSS 进程常驻内存(字节),需 psutil 同上
261
+
262
+ 调用树 父函数数 调用该函数的不同父函数数量 record_parent=True
263
+
264
+ 子调用总数 该函数调用的其他函数总次数 record_children=True
265
+
266
+ 所有扩展指标默认关闭,确保零额外性能开销。仅在需要时显式开启。
267
+
268
+ ## 🧠 高级功能
269
+ 1️⃣ 轻量模式 (lite_mode=True)
270
+
271
+ 不再记录 min_time / max_time / min_cpu / max_cpu。
272
+
273
+ 减少约 30% 的内存占用和计算开销。
274
+
275
+ 2️⃣ 采样统计 (sample_rate=0.1)
276
+
277
+ 只有 10% 的调用会被真正检测并记录。
278
+
279
+ 适用于极高频率调用的函数(如每毫秒执行一次)。
280
+
281
+ 3️⃣ 慢调用阈值 (slow_threshold=0.01)
282
+
283
+ 只记录耗时超过 0.01 秒的调用。
284
+
285
+ 自动过滤掉绝大多数快速调用,聚焦性能瓶颈。
286
+
287
+ 4️⃣ 调用树追踪
288
+
289
+ 通过 record_parent / record_children 控制。
290
+
291
+ 在报告表格中显示 父函数数 和 子调用总数,快速识别热点路径。
292
+
293
+ 5️⃣ 资源监控 (需 psutil)
294
+
295
+ 在装饰器/上下文管理器开启时,额外记录 CPU 利用率 (%) 和 进程内存 RSS。
296
+
297
+ 报告表格中增加 CPU% 列。
298
+
299
+ ## ⚡ 性能开销说明
300
+ perfmon 在设计时始终将 低开销 作为首要目标:
301
+
302
+ 全局禁用:pm.disable() 后,所有装饰器直接返回原函数,无任何额外函数调用。
303
+
304
+ 采样:未命中采样的调用不执行任何测量代码。
305
+
306
+ 轻量模式:跳过 min/max 更新,减少数据存储操作。
307
+
308
+ 零依赖核心:基础指标仅使用 Python 内置模块。
309
+
310
+ 在典型场景下(仅开启时间测量),每个函数调用增加约 200~400ns 开销。
311
+ 开启内存检测会增加约 1~2µs(取决于 tracemalloc)。
312
+ 扩展指标(I/O、锁等)仅在对应操作发生时产生额外开销。
313
+
314
+ ## 🧩 扩展指南
315
+ perfmon 的设计易于扩展,您可以在 StatEntry 中添加新字段,在 Profiler.record 方法中增加参数,并在适当位置(如补丁函数、装饰器)调用 record 传递新指标。
316
+
317
+ 在 StatEntry.__slots__ 和 __init__ 中添加新字段。
318
+
319
+ 在 Profiler.record 方法中添加对应参数并记录到 stat。
320
+
321
+ 在需要采集数据的地方(如补丁函数、装饰器)调用 _PROFILER.record(...) 传递新指标。
322
+
323
+ 在 export_json 和 export_csv 中添加导出逻辑。
324
+
325
+ 示例:添加“数据库查询耗时”指标可参考 I/O 监控的实现。
326
+
327
+ ## 📝 完整示例
328
+ 示例1:综合检测(开启所有扩展)
329
+ python
330
+ ````
331
+ import perfmon as pm
332
+ import threading, requests, time
333
+
334
+ pm.configure(
335
+ monitor_io=True,
336
+ monitor_locks=True,
337
+ monitor_exceptions=True,
338
+ monitor_gc=True,
339
+ monitor_http=True,
340
+ monitor_cache=True,
341
+ resource_monitor=True
342
+ )
343
+
344
+ @pm.profile(memory=True, cpu=True)
345
+ def worker():
346
+ # 文件 I/O
347
+ with open('/tmp/test.txt', 'w') as f:
348
+ f.write('x' * 10000)
349
+ # 锁等待
350
+ lock = threading.Lock()
351
+ lock.acquire()
352
+ lock.release()
353
+ # HTTP 请求
354
+ requests.get('https://httpbin.org/get')
355
+ # 异常
356
+ try:
357
+ 1/0
358
+ except ZeroDivisionError:
359
+ pass
360
+
361
+ worker()
362
+ pm.report()
363
+ pm.export_json('full_report.json')
364
+ ````
365
+ 示例2:缓存命中率统计
366
+ python
367
+ ````
368
+ @pm.profile_cache(maxsize=5)
369
+ @pm.profile() # 双层装饰器,顺序无妨
370
+ def fib(n):
371
+ return n if n < 2 else fib(n-1) + fib(n-2)
372
+
373
+ fib(10)
374
+ fib(10) # 第二次命中缓存
375
+ print(fib.cache_info()) # 直接查看缓存统计
376
+ pm.report() # 缓存命中/未命中会出现在表格中
377
+ ````
378
+ 示例3:采样 + 轻量模式
379
+ python
380
+ ````
381
+ pm.configure(lite_mode=True, sample_rate=0.2)
382
+
383
+ @pm.profile()
384
+ def fast():
385
+ for _ in range(1000):
386
+ pass
387
+
388
+ for _ in range(1000):
389
+ fast()
390
+
391
+ pm.report() # 只记录了约200次调用,且无 min/max 列
392
+ ````
393
+ ## 📋 API 参考
394
+ ### 全局函数
395
+
396
+ 函数 描述
397
+
398
+ profile(...) 函数性能检测装饰器
399
+
400
+ profile_cache(maxsize=128) 缓存命中率检测装饰器
401
+
402
+ profile_context(name, ...) 代码块上下文管理器
403
+
404
+ profile_file(filename, ...) 执行并检测整个 Python 文件
405
+
406
+ configure(...) 动态修改全局配置
407
+
408
+ enable() / disable() 全局启用/禁用检测
409
+
410
+ reset() 清空所有统计数据
411
+
412
+ report(sort_by='total_time') 打印统计表格
413
+
414
+ export_json(filepath) / export_csv(filepath) 导出统计数据到文件
415
+
416
+ ### 配置项详解
417
+ 配置参数 类型 默认值 说明
418
+
419
+ lite_mode bool False 轻量模式
420
+
421
+ sample_rate float 1.0 采样率 0.0~1.0
422
+
423
+ slow_threshold float 0.0 慢调用阈值(秒)
424
+
425
+ record_parent bool True 记录调用者
426
+
427
+ record_children bool True 记录子调用
428
+
429
+ resource_monitor bool False 启用 psutil 资源监控
430
+
431
+ monitor_io bool False 监控文件 I/O 耗时
432
+
433
+ monitor_locks bool False 监控锁等待时间
434
+
435
+ monitor_exceptions bool False 监控异常类型
436
+
437
+ monitor_gc bool False 监控 GC 暂停
438
+
439
+ monitor_http bool False 监控 HTTP 请求(需 requests)
440
+
441
+ monitor_cache bool False 监控缓存命中率(配合 profile_cache)
442
+
443
+ ## 🤝 贡献指南
444
+ 欢迎贡献代码、报告问题或提出新功能建议!
445
+
446
+ 你可以将贡献的代码发给我,Email:FourWaterLeaf@163.com
447
+
448
+ ## 许可证
449
+ MIT