返回顶部
p

perf-profiler性能分析器

Profile and optimize application performance. Use when diagnosing slow code, measuring CPU/memory usage, generating flame graphs, benchmarking functions, load testing APIs, finding memory leaks, or optimizing database queries.

作者: admin | 来源: ClawHub
源自
ClawHub
版本
V 1.0.0
安全检测
已通过
2,914
下载量
免费
免费
2
收藏
概述
安装方式
版本历史

perf-profiler

性能分析器

测量、分析和优化应用程序性能。涵盖CPU分析、内存分析、火焰图、基准测试、负载测试以及特定语言的优化模式。

何时使用

  • - 诊断应用程序或函数运行缓慢的原因
  • 测量CPU和内存使用情况
  • 生成火焰图以可视化热点路径
  • 对函数或端点进行基准测试
  • 在部署前对API进行负载测试
  • 发现并修复内存泄漏
  • 优化数据库查询性能
  • 比较变更前后的性能

快速计时

命令行计时

bash

为任何命令计时


time my-command --flag

更精确:多次运行并统计

for i in $(seq 1 10); do /usr/bin/time -f %e my-command 2>&1 done | awk {sum+=$1; sumsq+=$1*$1; count++} END { avg=sum/count; stddev=sqrt(sumsq/count - avg*avg); printf runs=%d avg=%.3fs stddev=%.3fs\n, count, avg, stddev }

Hyperfine(更好的基准测试工具)

安装:https://github.com/sharkdp/hyperfine

hyperfine command-a command-b hyperfine --warmup 3 --runs 20 my-command hyperfine --export-json results.json old-version new-version

内联计时(任何语言)

javascript
// Node.js
console.time(operation);
await doExpensiveThing();
console.timeEnd(operation); // operation: 142.3ms

// 高精度
const start = performance.now();
await doExpensiveThing();
const elapsed = performance.now() - start;
console.log(Elapsed: ${elapsed.toFixed(2)}ms);

python

Python


import time

start = time.perf_counter()
doexpensivething()
elapsed = time.perf_counter() - start
print(fElapsed: {elapsed:.4f}s)

上下文管理器

from contextlib import contextmanager

@contextmanager
def timer(label=):
start = time.perf_counter()
yield
elapsed = time.perf_counter() - start
print(f{label}: {elapsed:.4f}s)

with timer(data processing):
process_data()

go
// Go
start := time.Now()
doExpensiveThing()
fmt.Printf(Elapsed: %v\n, time.Since(start))

Node.js 分析

使用V8检查器进行CPU分析

bash

生成CPU分析文件(写入.cpuprofile文件)


node --cpu-prof app.js

在Chrome DevTools > Performance标签页中打开.cpuprofile文件

为特定持续时间生成分析文件

node --cpu-prof --cpu-prof-interval=100 app.js

检查正在运行的进程

node --inspect app.js

在Chrome中打开chrome://inspect,点击inspect

转到Performance标签页,点击Record

堆快照(内存)

bash

生成堆快照


node --heap-prof app.js

通过编程方式获取快照

node -e const v8 = require(v8); const fs = require(fs);

// 获取快照
const snapshotStream = v8.writeHeapSnapshot();
console.log(Heap snapshot written to:, snapshotStream);

比较堆快照以查找泄漏:

1. 获取快照A(基准线)

2. 运行可能泄漏的操作

3. 获取快照B

4. 在Chrome DevTools > Memory中,加载两者并使用Comparison视图

内存使用监控

javascript
// 定期打印内存使用情况
setInterval(() => {
const usage = process.memoryUsage();
console.log({
rss: ${(usage.rss / 1024 / 1024).toFixed(1)}MB,
heapUsed: ${(usage.heapUsed / 1024 / 1024).toFixed(1)}MB,
heapTotal: ${(usage.heapTotal / 1024 / 1024).toFixed(1)}MB,
external: ${(usage.external / 1024 / 1024).toFixed(1)}MB,
});
}, 5000);

// 检测内存增长
let lastHeap = 0;
setInterval(() => {
const heap = process.memoryUsage().heapUsed;
const delta = heap - lastHeap;
if (delta > 1024 * 1024) { // > 1MB增长
console.warn(Heap grew by ${(delta / 1024 / 1024).toFixed(1)}MB);
}
lastHeap = heap;
}, 10000);

Node.js 基准测试

javascript
// 简单的基准测试函数
function benchmark(name, fn, iterations = 10000) {
// 预热
for (let i = 0; i < 100; i++) fn();

const start = performance.now();
for (let i = 0; i < iterations; i++) fn();
const elapsed = performance.now() - start;

console.log(${name}: ${(elapsed / iterations).toFixed(4)}ms/op (${iterations} iterations in ${elapsed.toFixed(1)}ms));
}

benchmark(JSON.parse, () => JSON.parse({key:value,num:42}));
benchmark(regex match, () => /^\d{4}-\d{2}-\d{2}$/.test(2026-02-03));

Python 分析

cProfile(内置CPU分析器)

bash

分析脚本


python3 -m cProfile -s cumulative my_script.py

保存到文件以便分析

python3 -m cProfile -o profile.prof my_script.py

分析保存的分析文件

python3 -c import pstats stats = pstats.Stats(profile.prof) stats.sort_stats(cumulative) stats.print_stats(20)

分析特定函数

python3 -c import cProfile from mymodule import expensivefunction

cProfile.run(expensive_function(), sort=cumulative)

line_profiler(逐行分析)

bash

安装


pip install line_profiler

在感兴趣的函数上添加@profile装饰器,然后:

kernprof -l -v my_script.py

python

编程式使用


from line_profiler import LineProfiler

def process_data(data):
result = []
for item in data: # 这个循环是瓶颈吗?
transformed = transform(item)
if validate(transformed):
result.append(transformed)
return result

profiler = LineProfiler()
profiler.addfunction(processdata)
profiler.enable()
processdata(largedataset)
profiler.disable()
profiler.print_stats()

内存分析(Python)

bash

memory_profiler


pip install memory_profiler

逐行分析内存

python3 -m memoryprofiler myscript.py

python
from memory_profiler import profile

@profile
def load_data():
data = []
for i in range(1000000):
data.append({id: i, value: fitem_{i}})
return data

随时间跟踪内存

import tracemalloc

tracemalloc.start()

... 运行代码 ...

snapshot = tracemalloc.take_snapshot()
top_stats = snapshot.statistics(lineno)
for stat in top_stats[:10]:
print(stat)

Python 基准测试

python
import timeit

对语句计时

result = timeit.timeit(sorted(range(1000)), number=10000) print(fsorted: {result:.4f}s for 10000 iterations)

比较两种方法

setup = data = list(range(10000)) t1 = timeit.timeit(list(filter(lambda x: x % 2 == 0, data)), setup=setup, number=1000) t2 = timeit.timeit([x for x in data if x % 2 == 0], setup=setup, number=1000) print(ffilter: {t1:.4f}s | listcomp: {t2:.4f}s | speedup: {t1/t2:.2f}x)

pytest-benchmark

pip install pytest-benchmark

def test_sort(benchmark):

benchmark(sorted, list(range(1000)))

Go 分析

内置pprof

go
// 添加到main.go以实现HTTP可访问的分析
import (
net/http
_ net/http/pprof
)

func main() {
go func() {
http.ListenAndServe(localhost:6060, nil)
}()
// ... 应用程序其余部分
}

bash

CPU

标签

skill ai

通过对话安装

该技能支持在以下平台通过对话安装:

OpenClaw WorkBuddy QClaw Kimi Claude

方式一:安装 SkillHub 和技能

帮我安装 SkillHub 和 perf-profiler-1775983508 技能

方式二:设置 SkillHub 为优先技能安装源

设置 SkillHub 为我的优先技能安装源,然后帮我安装 perf-profiler-1775983508 技能

通过命令行安装

skillhub install perf-profiler-1775983508

下载

⬇ 下载 perf-profiler v1.0.0(免费)

文件大小: 6.97 KB | 发布时间: 2026-4-13 11:26

v1.0.0 最新 2026-4-13 11:26
Initial release: CPU/memory profiling for Node.js/Python/Go, flame graphs, benchmarking, load testing, memory leak detection, database query optimization

Archiver·手机版·闲社网·闲社论坛·羊毛社区· 多链控股集团有限公司 · 苏ICP备2025199260号-1

Powered by Discuz! X5.0   © 2024-2025 闲社网·线报更新论坛·羊毛分享社区·http://xianshe.com

p2p_official_large
返回顶部