Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to calculate execution time of a async method in c#

So I have a Async method which does something asynchronously.

private async static void DoSomethingAsync (int i){}

I call it in a loop lets say 50 times.

for (int i = 0; i < 50; i++)
 {
    DoSomethingAsync (i);
 }

At the end of loop I want to calculate total processing time, I used Stopwatch but as you can imagine it gives me wrong time as it gets called as soon as after the loop, it does not wait for the DoSomethingAsync to finish processing.

how to tell Stopwatch to wait for all the 50 instances of DoSomethingAsync() to finish. I have seen this question, but I cant use Task here.

like image 536
ahsant Avatar asked May 24 '18 05:05

ahsant


People also ask

How do you calculate Execution time?

The difference between the end time and start time is the execution time. Get the execution time by subtracting the start time from the end time.

What happens when you call async method?

The call to the async method starts an asynchronous task. However, because no Await operator is applied, the program continues without waiting for the task to complete. In most cases, that behavior isn't expected.

Does async await use thread pool?

The async and await keywords don't cause additional threads to be created. Async methods don't require multithreading because an async method doesn't run on its own thread. The method runs on the current synchronization context and uses time on the thread only when the method is active.

Does async await improve performance?

The main benefits of asynchronous programming using async / await include the following: Increase the performance and responsiveness of your application, particularly when you have long-running operations that do not require to block the execution.


1 Answers

I don't know why you cannot use Task, my guess is that you are calling it within a Main method or something. So i will go out from that.

Like Martin Ullrich said i would change DoSomethingAsync method to return a task:

private async static Task DoSomethingAsync(int i)
{
    ...
}

Then create a new method that does the loop by adding the methods to a List<Task>:

private static async void PerformLoop()
{
    Stopwatch timer = new Stopwatch();
    timer.Start();
    List<Task> l = new List<Task>();
    for (int i = 0; i < 50; i++)
    {
        l.Add(DoSomethingAsync(i));
    }
    await Task.WhenAll(l);
    timer.Stop();

    Console.WriteLine(timer.Elapsed.TotalSeconds);
}

Now from where you did the loop before, in this case the Main method simply add the new method call in there:

static void Main(string[] args)
{
    PerformLoop();

    Console.ReadLine();
}
like image 176
Mike Avatar answered Oct 27 '22 00:10

Mike