簡體   English   中英

如何統計await方法的執行時間

[英]How to count await method execution time

我正在做一個 dot.net 核心項目。 其中我必須計算我的 await 方法在執行時占用了多少。

[HttpPost]
public async Task<bool> InsertIntoDatabase([Frombody] StudentModel objStu) {
//For Each method and other stuff
  await DoInsert(Fiels Details);
}

我在 Ajax 調用這個方法。所以在成功執行代碼后,我想返回該方法所用的次數(以分鍾為單位)。

此插入過程包含 500 多條記錄。 所以,我有興趣計算時間

一種方法是使用Stopwatch

[HttpPost]
public async Task<bool> InsertIntoDatabase([Frombody] StudentModel student) 
{
    var clock = new Stopwatch();
    clock.Start();

    await DoInsert(student);

    clock.Stop();
    var minutes = clock.Elapsed.TotalMinutes();
}

秒表 Class

為什么不在您的任務中返回一個帶有時間和結果的自定義 object?

private async Task<MyClass> GetResult()
{}

public class MyClass
{
    public bool  Success { get; set; }
    public long TimeInSeconds { get; set; }
}

我強烈建議您查看MiniProfiler 設置起來非常容易!

  1. 通過 Nuget 安裝 MiniProfiler
  2. 將 MiniProfiler 標簽助手添加到您的 _Layout.cshtml
  3. 將 MiniProfiler 標簽 ( <mini-profiler /> ) 添加到您的 HTML (我也將我的放在 Layout.cshtml 中)
  4. 在Startup.cs中添加服務:
services.AddMiniProfiler(options =>
{
    options.RouteBasePath = "/profiler";
    options.SqlFormatter = new SqlServerFormatter();
});
  1. 在調用app.UseStaticFiles()之后添加:
if (env.IsDevelopment())
{
     app.UseMiniProfiler();
}

現在 MiniProfiler 已准備好 go 並且只會出現在開發中(第 5 步)。 要分析一些代碼,請執行以下操作:

using (MiniProfiler.Current.Step("This Will be the label displayed on the front end"))
{
    //code you want to profile
}

現在運行你的代碼,瞧。 MiniProfiler 將在您的頁面上放置一個非常小的表格(我認為它默認為左上角)。 每行都是請求的過去(也適用於 AJAX!)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM