什么是计算时间跨度的最佳方法 [英] What is Best way to calculate time span

查看:337
本文介绍了什么是计算时间跨度的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的c#程序中,我的要求是计算业务逻辑执行的时间间隔,这是在foreach循环里面我必须存储时间段。

In my c# program, my requirement is to calculate a timespan for business logic execution that is inside a foreach loop I have to store time span.

我正在使用以下代码

for (int i = 0; i < 100; i++)
{
    DateTime start= DateTime.Now; 
    // Business logic
    DateTime end= DateTime.Now; 
    TimeSpan time = start.Subtract(end);
    // Save timespan in log file
}

请更正我是否我正在使用正确的代码,或者我需要修改以获得更好的性能和结果。

Please correct me whether I am using right code, or do I need to modify for better performance and result.

推荐答案

你应该使用 秒表 秒表比时间测量更准确。

You should use a Stopwatch. The Stopwatch is much more accurate for time measurement than the wall time clock.

var sw = Stopwatch.StartNew();
// business logic
sw.Stop();
TimeSpan time = sw.Elapsed;

这篇关于什么是计算时间跨度的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆