mirror of
https://github.com/unknwon/the-way-to-go_ZH_CN.git
synced 2025-08-11 23:52:31 +08:00
896 B
896 B
13.10 性能调试:分析并优化 Go 程序
13.10.1 时间和内存消耗
可以用这个便捷脚本 xtime 来测量:
#!/bin/sh
/usr/bin/time -f ‘%Uu %Ss %er %MkB %C’ “$@”
在 Unix 命令行中像这样使用 xtime goprogexec
,这里的 progexec 是一个 Go 可执行程序,这句命令行输出类似:56.63u 0.26s 56.92r 1642640kB progexec,分别对应用户时间,系统时间,实际时间和最大内存占用。
13.10.2 用 go test 调试
如果代码使用了 Go 中 testing 包的基准测试功能,我们可以用 gotest 标准的 -cpuprofile
和 -memprofile
标志向指定文件写入 CPU 或 内存使用情况报告。
使用方式:go test -x -v -cpuprofile=prof.out -file x_test.go
编译执行 x_test.go 中的测试,并向 prof.out 文件中写入 cpuprofile 信息。