<p>Hi!</p>
<p>I'm looking for a way to do some request-scoped profiling on a Go HTTP server.</p>
<p>All profiling tools seem to be process-wide.</p>
<p>Is there any way to limit the scope? The idea would be to be able to do something like this:</p>
<pre><code>func someFunc(){
scopedProfile := startScopedProfiling()
// Do something
scopedProfile.Stop()
// Here, scoped profile would contain memory, CPU, and trace information only about what happened between start and stop
}
</code></pre>
<p>I've done my research and found nothing. I understand it might be complicated to do, but maybe someone has a tool/idea for this?</p>
<p>If nothing already exists, I'm thinking of using the process-wide tools, and somehow trim the data.</p>
<hr/>**评论:**<br/><br/>tv64738: <pre><p>You can't tell a sampling based profiler what it will see, only when to look.</p></pre>TheMerovius: <pre><p>In theory, <a href="https://golang.org/pkg/runtime/trace/" rel="nofollow">runtime/trace</a> <em>might</em> help you, though you probably have to force it a bit to give you useful information. This might get you an execution trace, which is pretty much as useful as a profile. Or it might not, I haven't looked at what <em>exactly</em> they log.</p>
<p>Apart from that you could manually instrument your code to do request-scoped tracing. It's not very hard to do in principle, it's somewhat harder to do in practice (though totally doable) and you will incur a performance-impact even if you don't trace.</p>
<p>A profile, as in pprof, you can't request-scope, unless you could somehow force the runtime to only execute the code belonging to this particular request and stop everything else. I don't think that's realistic.</p></pre>dlsniper: <pre><p>See the article: <a href="https://blog.golang.org/profiling-go-programs" rel="nofollow">https://blog.golang.org/profiling-go-programs</a> and instead of profiling main, profile what you need. Also you could write benchmarks and run them only for that function.</p></pre>HectorJ: <pre><p><a href="https://golang.org/pkg/runtime/pprof/#StartCPUProfile" rel="nofollow">https://golang.org/pkg/runtime/pprof/#StartCPUProfile</a></p>
<blockquote>
<p>StartCPUProfile enables CPU profiling for the current process.</p>
</blockquote>
<p>As I understand it, no matter where you start it you will still get CPU profiling from other running goroutines.</p>
<p>Edit: also this is for live profiling, so sadly the benchmark approach does not fit my case.</p></pre>dlsniper: <pre><p>I am not aware of of any tools to do what you want. The closest you can get is to drill down the profile you get out of the debugged process from the function you need.</p></pre>
![](https://static.golangjob.cn/static/img/banner.png)