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

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

问题描述

在我的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天全站免登陆