您的位置:首页 > 编程语言 > C#

Understanding StopWatch Class In C#

2012-04-01 20:28 417 查看
Stopwatch instance can measure elapsed time for one interval, or the total of elapsed time across multiple intervals. In a typical Stopwatch scenario, you call the Startmethod, then eventually call the Stop method, and then you check elapsed time using the Elapsed property. (From MSDN)

Let say i want to find out Total Time a Process has been Running.
Like
1. How many Minutes or Second it took to insert 1000 record in Database?
2. How many time it took to update the Database ? etc ..

I provide a very Basic Example with a Console Application ..

The Stopwatch Class has two Primary Methods 1. Start() 2. Stop() and One Property that is Elapsed .

The Code:

using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;

namespace StopWatchExample
{
class Program
{
static void Main(string[] args)
{
Stopwatch sw = new Stopwatch();
sw.Start();
Console.WriteLine("Stop Watch Start....\n");
for (int i = 1; i <= 5; i++)
{
Console.WriteLine(i + "\n");
}
sw.Stop();
Console.WriteLine("Stop Watch Stopped:");
Console.WriteLine("Total Time: {0}", sw.Elapsed);
Console.ReadLine();
}
}
}


As You can See I have started our Stopwatch Just Before My loop has started.
Now the Loop will Do its work ..
After That As Soon As we are out sw.Stop has been Called.

I have Just Recorded The Timing The Loop Took To Complete.

The Output Will Look SomeThing Like These:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: