如何计算等待方法执行时间



我正在做一个dot-net核心项目。在其中,我必须计算在执行时等待方法占用了多少。

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

秒表等级

为什么不在任务中返回一个带有时间和结果的自定义对象?

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已经准备就绪,并且只会出现在开发中(步骤5(。要配置某些代码,请执行:

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

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

最新更新