Seggie
Seggie

Reputation: 535

Is this the best way to get the time it takes to run an async task?

I want to find out how long it takes to execute my async tasks, so that I can improve on the execution time.

Please look at the test method and advise. Test background: I want to find out the user account manager from Active Directory given the sAMACcountName.

[TestMethod]
public async Task GetManagerAsync_TestMethod()
{
    // connect to the Active Directory
    var serviceUsers = new User(@"LDAP://XXXXXXXXX", @"USER", "PASSWORD");

    // get the time before the start of operation
    var sTime = DateTime.Now;

    // perform the task
    var task = await serviceUsers.GetManagerAsync(@"sAMAccountName");

    // get the time after the operation
    var eTime = DateTime.Now;

    // get the time span between the start and end time
    TimeSpan taskRunTime = eTime - sTime;

    System.Diagnostics.Debug.WriteLine("Operation took {0} seconds", taskRunTime.TotalSeconds);

    Assert.IsNotNull(task);
 }

Upvotes: 2

Views: 4366

Answers (1)

dcastro
dcastro

Reputation: 68670

You should be using a Stopwatch instead.

var stopwatch = Stopwatch.StartNew();
var task = await serviceUsers.GetManagerAsync(@"sAMAccountName");
stopwatch.Stop();

var elapsed = stopwatch.Elapsed;

Not only is it more semantically correct, it's also way more accurate:

If the installed hardware and operating system support a high-resolution performance counter, then the Stopwatch class uses that counter to measure elapsed time. Otherwise, the Stopwatch class uses the system timer to measure elapsed time.

Upvotes: 9

Related Questions