gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 19:39:30 25 4
gpt4 key购买 nike

我想知道执行我的异步任务需要多长时间,以便我可以改进执行时间。

请看测试方法并指教。测试背景:我想在给定 sAMACcountName 的情况下从 Active Directory 中找出用户帐户管理员。

[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相反。

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

var elapsed = stopwatch.Elapsed;

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

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.

关于c# - 这是获得运行异步任务所需时间的最佳方式吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27441303/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com