'How to count await method execution time

I am working on a dot net core project. In which I have to count how much had taken by my await method while executing.

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

I am calling this method in Ajax. So after successful execution of code, I want to return the number of times in minutes taken by the method.

This insertion process contains 500+ records. So, I am interested to calculate the time



Solution 1:[1]

Why not return a custom object in your task with the time and the result?

private async Task<MyClass> GetResult()
{}

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

Solution 2:[2]

I would highly recommend checking out MiniProfiler. It's extremely easy to setup!

  1. Install MiniProfiler via Nuget
  2. Add the MiniProfiler tag helper to your _Layout.cshtml
  3. Add the MiniProfiler tag (<mini-profiler />) to your HTML (I put mine in Layout.cshtml as well)
  4. Add to services in Startup.cs:
services.AddMiniProfiler(options =>
{
    options.RouteBasePath = "/profiler";
    options.SqlFormatter = new SqlServerFormatter();
});
  1. Add this AFTER calling app.UseStaticFiles():
if (env.IsDevelopment())
{
     app.UseMiniProfiler();
}

Now MiniProfiler is ready to go and will only appear in development (step 5). To profile some code do:

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

Now run your code and voila! MiniProfiler will put a very small table on your page (I THINK it defaults top left). Each row is the elapsed of the request (works with AJAX too!).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Niels de Schrijver
Solution 2 Seth