You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让go tool pprof定期采集性能分析数据?

如何让pprof定期获取性能分析数据?

要实现pprof定期采集性能数据,主要有以下几种实用方案:

1. 用Shell脚本循环执行采集

这是最直接的方式,通过脚本循环调用pprof命令,每次采集后保存到带时间戳的文件中,方便后续分析。示例脚本如下:

#!/bin/bash
# 采集间隔(单位:秒,这里设为5分钟)
INTERVAL=300
# 每次采集持续时间(和你原来的60秒一致)
DURATION=60
# 保存采集文件的目录
OUTPUT_DIR="./pprof_profiles"

# 创建输出目录(不存在则创建)
mkdir -p "$OUTPUT_DIR"

while true; do
    # 生成带时间戳的文件名,避免覆盖
    TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
    OUTPUT_FILE="$OUTPUT_DIR/profile_${TIMESTAMP}.pb.gz"
    
    # 执行采集并保存到文件(不再启动HTTP服务,专注于存数据)
    go tool pprof -output "$OUTPUT_FILE" http://localhost:6060/debug/pprof/profile?seconds=$DURATION
    
    echo "已保存性能分析文件:$OUTPUT_FILE"
    # 等待下一次采集
    sleep $INTERVAL
done

使用时,将脚本保存为pprof_cron.sh,赋予执行权限chmod +x pprof_cron.sh,然后运行即可。如果需要每次采集后临时查看数据,可以在脚本中添加启动HTTP服务的命令,但注意要避免端口冲突(比如每次用随机端口)。

2. 用系统定时任务(Crontab/Windows任务计划)

如果不需要持续运行脚本,可借助系统定时任务工具,按固定周期执行单次采集命令:

Linux/macOS(Crontab)

编辑crontab配置:

crontab -e

添加如下规则(示例为每小时执行一次采集,保存到指定目录):

0 * * * * /usr/bin/go tool pprof -output /opt/pprof_profiles/profile_$(date +\%Y\%m\%d_\%H\%M\%S).pb.gz http://localhost:6060/debug/pprof/profile?seconds=60

注意:Crontab中%需要转义为\%,否则会被解析为换行符;确保go命令的路径正确(可用which go查看)。

Windows(任务计划程序)

  1. 创建一个批处理文件pprof_cron.bat,内容如下:
@echo off
set TIMESTAMP=%date:~0,4%%date:~5,2%%date:~8,2%_%time:~0,2%%time:~3,2%%time:~6,2%
set OUTPUT_FILE=C:\pprof_profiles\profile_%TIMESTAMP%.pb.gz
mkdir C:\pprof_profiles 2>nul
go tool pprof -output "%OUTPUT_FILE%" http://localhost:6060/debug/pprof/profile?seconds=60
  1. 打开「任务计划程序」,创建定时任务,设置触发周期(如每小时),并将操作设置为运行这个批处理文件。

3. 程序内定时导出(针对自研Go服务)

如果你有权限修改目标Go服务的代码,可以直接在程序中定时导出pprof数据,无需依赖外部命令:

package main

import (
    "log"
    "os"
    "runtime/pprof"
    "time"
)

func init() {
    // 每5分钟执行一次CPU profiling
    go func() {
        ticker := time.NewTicker(5 * time.Minute)
        defer ticker.Stop()
        for range ticker.C {
            timestamp := time.Now().Format("20060102_150405")
            f, err := os.Create("./pprof/profile_" + timestamp + ".pb.gz")
            if err != nil {
                log.Printf("create profile file failed: %v", err)
                continue
            }
            if err := pprof.StartCPUProfile(f); err != nil {
                log.Printf("start CPU profile failed: %v", err)
                f.Close()
                continue
            }
            // 采集60秒数据
            time.Sleep(60 * time.Second)
            pprof.StopCPUProfile()
            f.Close()
            log.Printf("saved profile: %s", f.Name())
        }
    }()
}

func main() {
    // 你的服务逻辑
    select {}
}

后续分析

采集到的.pb.gz文件,可随时用以下命令启动HTTP服务查看:

go tool pprof -no_browser -http=0.0.0.0:8081 /path/to/profile_20240520_143000.pb.gz

内容的提问来源于stack exchange,提问作者daisy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 04:30:48