C# 这是获得运行异步任务所需时间的最佳方法吗?

C# 这是获得运行异步任务所需时间的最佳方法吗?,c#,async-await,C#,Async Await,我想知道执行异步任务需要多长时间,以便提高执行时间 请查看测试方法并提出建议。测试背景:我想从Active Directory中找到给定sAMACcountName的用户帐户管理器 [TestMethod] public async Task GetManagerAsync_TestMethod() { // connect to the Active Directory var serviceUsers = new User(@"LDAP://XXXXXXXXX", @"USE

我想知道执行异步任务需要多长时间,以便提高执行时间

请查看测试方法并提出建议。测试背景:我想从Active Directory中找到给定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);
 }
你应该改用一个

它不仅在语义上更加正确,而且更加准确:

如果安装的硬件和操作系统支持高分辨率性能计数器,则Stopwatch类将使用该计数器测量经过的时间。否则,Stopwatch类使用系统计时器来测量经过的时间


使用秒表相关读数:。你(至少)犯了一个错误。#5.来自@Heinzi的链接:“
DateTime。现在
只比那只外祖父的时钟稍微好一点:它只每隔几毫秒滴答一次。更糟糕的是,机器之间滴答的速度并不是固定的。”@dcastro感谢你的精彩表演,我只是想快速地强调一下我的困境。我投票结束这个问题,因为它属于代码审查。谢谢@dcastro,它比我的选项好,它将我的代码镜头方法的可维护性提高了2分。
var stopwatch = Stopwatch.StartNew();
var task = await serviceUsers.GetManagerAsync(@"sAMAccountName");
stopwatch.Stop();

var elapsed = stopwatch.Elapsed;