C# - 测量经过时间的最有效方法

时间:2021-02-23 12:44:58

标签: c# performance time memory-efficient

我正在开发一个 C# 控制台应用程序,在该应用程序中我需要知道自程序启动以来经过的时间。
我有一个存储开始时间的变量 (DateTime now = DateTime.Now;)

测量经过时间的最有效方法是什么?
经过的时间可能是几个小时 - 这就是我担心效率和内存使用情况的原因。

提前致谢!

2 个答案:

答案 0 :(得分:1)

从程序开始的时间减去当前时间。这将返回一个 TimeSpan,它公开 properties 之类的 TotalHours,您可以使用它来计算经过的时间。

// on start
var startTime = DateTime.UtcNow;

// later on, to see hours elapsed since then
var elapsed = (DateTime.UtcNow - startTime).TotalHours;

答案 1 :(得分:0)

别担心。测量时间跨度不使用任何资源,因为它只是比较现在和那时。

public async Task<List<Customer>> FetchCustomers(string userId, List<string> userRoles, string userEmail)
{
    if (userRoles.Contains("Admin"))
    {
         customer = _context.Customers;
    }
    else if (userRoles.Contains("Project Manager") ||
             userRoles.Contains("Business Analyst") ||
             userRoles.Contains("Developer"))
    {
         if (userRoles.Contains("Project Manager"))
         {
             customers = customers.Where(c => c.ProjectManager.ProjectManagerId == userId
                       || c.Projects.Any(op =>                                              
                          op.ProjectsCompleted.Any(assignee =>                                                           
                          assignee.UserId == userId)));
         }
         if (userRoles.Contains("Business Analyst"))
         {
             var allPossibleCustomers = _context.Customers.Where(c =>
                            c.Projects.Any(op => op.BusinessAnalysts.Any(ba => ba.BusinessAnalystId == userId)));

             customers = customers?.Union(allPossibleCustomers) ?? allPossibleCustomers;
         }
         if (userRoles.Contains(Roles.Developer.GetDescription()))
         {
              var allPossibleCustomers = _context.Customers.Where(c =>
              c.Projects.Any(op => op.PREDevDevelopersAssigned.Any(ba => ba.DeveloperId == userId)));
                    
             customers = customers?.Union(allPossibleCustomers) ?? allPossibleCustomers;
         }
    }
    var listData = await PagingList<Customer>.CreatePageAsync(customers, page, limit);
    return listData;
}

除了用于开始的变量外,它不使用任何资源,它只是一个 64 位计数器。

请注意,对于较短的时间跨度,最好使用 DateTime start = DateTime.Now; // do some heavy calculation TimeSpan delta = DateTime.Now - start; // get the time that elapsed ,因为这不受开始和现在之间可能发生的时间调整的影响。

相关问题