简体   繁体   English

在异步 controller 中测量 http 请求的 CPU 时间

[英]Measuring cpu time for http request in async controller

I was reading google SRE book chapter on handling overload: https://sre.google/sre-book/handling-overload/我正在阅读关于处理过载的谷歌 SRE 书籍章节: https://sre.google/sre-book/handling-overload/

They mention:他们提到:

An interesting part of the puzzle is computing in real time the amount of resources—specifically CPU—consumed by each individual request.这个难题的一个有趣部分是实时计算每个单独请求所消耗的资源量,特别是 CPU。 This computation is particularly tricky for servers that don't implement a thread-per-request model, where a pool of threads just executes different parts of all requests as they come in, using nonblocking APIs.对于没有实现每个请求的线程 model 的服务器来说,这种计算特别棘手,其中线程池使用非阻塞 API 在所有请求进入时执行它们的不同部分。

I know in a thread-per-request model, we could simply call getrusage(RUSAGE_THREAD, &r);我知道在每个请求的线程 model 中,我们可以简单地调用 getrusage(RUSAGE_THREAD, &r); but in a ASP.net Controller with async methods it's not guaranteed that code before and after the "await" keyword will execute on the same thread.但是在具有异步方法的 ASP.net Controller 中,不能保证“await”关键字之前和之后的代码将在同一线程上执行。 and even if it does, it's possible the thread also executed code for other http request.即使是这样,线程也有可能为其他 http 请求执行代码。

So is there a way to measure how much cpu time an async function used.那么有没有办法测量异步 function 使用了多少 CPU 时间。

Managed memory allocations will cause GC work that is done in other threads.托管 memory 分配将导致在其他线程中完成的 GC 工作。 Caches are managed in other threads.缓存在其他线程中管理。

Measuring whatever in direct dependency of a request is misleading.测量直接依赖于请求的任何内容都是误导性的。

If you have performance issues, you should collect metrics, ETW traces, memory dumps and analyze them.如果您有性能问题,您应该收集指标、ETW 跟踪、memory 转储并分析它们。

Found one Nuget this provides this feature.找到了一个 Nuget 这提供了这个功能。

https://github.com/devizer/Universe.CpuUsage https://github.com/devizer/Universe.CpuUsage

Using the class CpuUsageAsyncWatcher使用 class CpuUsageAsyncWatcher

public void Configure(IApplicationBuilder app)
{
    // Here is a "middleware" that displays total CPU usage
    // of all the Tasks executed by ASP.NET Core pipeline during each http request
    app.Use(async (context, next) =>
    {
        CpuUsageAsyncWatcher watcher = new CpuUsageAsyncWatcher();
        await next.Invoke();
        watcher.Stop();
        Console.WriteLine($"Cpu Usage by http request is {watcher.GetSummaryCpuUsage()}");
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM