如何统计await方法执行时间

问题描述 投票:0回答:4

我正在开发一个.net核心项目。其中我必须计算我的await方法在执行时花费了多少时间。

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

我在Ajax中调用这个方法。因此,在成功执行代码后,我想返回该方法所花费的时间(以分钟为单位)。

此插入过程包含 500 多条记录。所以,我有兴趣计算一下时间

c# asp.net-mvc asp.net-core .net-core asp.net-mvc-5
4个回答
3
投票

一种方法是使用

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();
}

秒表班


0
投票

为什么不在任务中返回包含时间和结果的自定义对象?

private async Task<MyClass> GetResult()
{}

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

0
投票

我强烈建议您查看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 已准备就绪,只会出现在开发中(第 5 步)。要分析一些代码,请执行以下操作:

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

现在运行您的代码,瞧! MiniProfiler 会在您的页面上放置一个非常小的表格(我认为它默认位于左上角)。每行都是请求的经过时间(也适用于 AJAX!)。


0
投票

[HttpPost] { var stopwatch = Stopwatch.StartNew(); try { await DoInsert(objStu); stopwatch.Stop(); TimeSpan elapsedTime = stopwatch.Elapsed; double minutes = elapsedTime.TotalMinutes; return Ok(new { Success = true, ElapsedTimeInMinutes = minutes }); } catch (Exception ex) { return BadRequest(new { Success = false, ErrorMessage = ex.Message }); } }

© www.soinside.com 2019 - 2024. All rights reserved.