<p>I'm using the "os/exec" package to run a command/process aiming to extract its <strong>memory usage</strong> and <strong>CPU execution duration</strong>. </p>
<p>Using the following snippet, i wasn't able to extract any useful information. I think it's because the exec.Command has a synchronous call.</p>
<pre><code>cmd := exec.Command("command", "arg1", "arg2")
err := cmd.Run()
if err != nil {
log.Fatal(err)
}
fmt.Println("MaxRSS:", cmd.ProcessState.SysUsage().(*syscall.Rusage).Maxrss)
</code></pre>
<p>I wonder if i should use a kind of Async exec function or something.</p>
<p>I appreciate any help.</p>
<hr/>**评论:**<br/><br/>Sythe2o0: <pre><p><code>exec.Command</code> probably isn't a problem, as it's just a constructor. If you meant <code>cmd.Run</code>, then you make that into an asynchronous call by wrapping it in a goroutine: </p>
<pre><code>go func() {
err := cmd.Run()
if err != nil {
log.Fatal(err)
}
}()
</code></pre>
<p>You could do something like this to monitor it: <a href="https://play.golang.org/p/KOu4qB6jEv" rel="nofollow">https://play.golang.org/p/KOu4qB6jEv</a> (I haven't run this myself, there's potential errors)</p>
<p>Alternatively, from the <a href="https://golang.org/pkg/os/exec/#Cmd.Start" rel="nofollow">docs</a>, use <code>cmd.Start</code></p></pre>nhooyr: <pre><p>Definitely use cmd.Start() otherwise there is a race because you won't know when the command has started in another goroutine.</p>
<p>Waiting for a second does not solve that race, just makes it much less likely.</p></pre>Sythe2o0: <pre><p>Sure, I made an assumption that the print would just print bogus data if the command had yet to start.</p></pre>CipheredBytes: <pre><p>Appreciate that. </p>
<ul>
<li>Timing can be monitored with <em>cmd.Start</em> and <em>cmd.Wait</em></li>
<li>Memory usage can be monitored with <em>cmd.Start</em> or <em>cmd.Run</em></li>
</ul></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传