使用golang运行可执行文件时,测量内存使用情况。

huangapple go评论68阅读模式
英文:

Measuring memory usage of executable run using golang

问题

通过os/exec包在Golang中运行的可执行文件,我如何测量其使用的内存量?最好是通过操作系统本身来完成吗?

英文:

How do I measure the amount of memory used by an executable which I run through the os/exec package in Golang? Is it better to do this through the OS itself?

答案1

得分: 11

你需要通过操作系统本身来完成这个任务。如果你使用的是Plan9或Posix系统,Go语言将会通过ProcessState.SysUsage()方法返回操作系统中的使用情况。

cmd := exec.Command("command", "arg1", "arg2")
err := cmd.Run()
if err != nil {
    log.Fatal(err)
}
// 为了避免发生panic,需要进行类型断言
fmt.Println("MaxRSS:", cmd.ProcessState.SysUsage().(*syscall.Rusage).Maxrss)

注意:不同的平台可能以字节或千字节为单位返回这个值。请查阅man getrusage获取详细信息。

英文:

You need to do this through the OS itself. If you are on plan9 or posix, Go will return the usage values from the OS for you in the structure returned by ProcessState.SysUsage().

cmd := exec.Command("command", "arg1", "arg2")
err := cmd.Run()
if err != nil {
	log.Fatal(err)
}
// check this type assertion to avoid a panic
fmt.Println("MaxRSS:", cmd.ProcessState.SysUsage().(*syscall.Rusage).Maxrss)

Note: different platforms may return this in bytes or kilobytes. Check man getrusage for details.

huangapple
  • 本文由 发表于 2014年12月24日 02:10:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/27625787.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定