Sei sulla pagina 1di 7

Stopwatch Class

.NET Framework 4

7 out of 10 rated this helpful

Provides a set of methods and properties that you can use to accurately measure elapsed time.

Inheritance Hierarchy
System.Object
System.Diagnostics.Stopwatch

Namespace: System.Diagnostics
Assembly: System in System.dll

Syntax
C#
publicclassStopwatch

The Stopwatch type exposes the following members.

Constructors
Name

Description

Stopwatch

Initializes a new instance of the Stopwatch class.

Show:

Inherited

Protected

Show:

Inherited

Protected

Show:

Inherited

Protected

Top

Properties
Name

Description

Elapsed

Gets the total elapsed time measured by the current instance.

ElapsedMilliseconds

Gets the total elapsed time measured by the current instance, in milliseconds.

ElapsedTicks

Gets the total elapsed time measured by the current instance, in timer ticks.

IsRunning

Gets a value indicating whether the Stopwatch timer is running.

Top

Methods
Name

Description

EqualsObject

Determines whether the specified Object is equal to the current Object. Inherited from Object.

Finalize

Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. Inherited from
Object.

GetHashCode

Serves as a hash function for a particular type. Inherited from Object.

GetTimestamp

Gets the current number of ticks in the timer mechanism.

GetType

Gets the Type of the current instance. Inherited from Object.

MemberwiseClone

Creates a shallow copy of the current Object. Inherited from Object.

Reset

Stops time interval measurement and resets the elapsed time to zero.

Restart

Stops time interval measurement, resets the elapsed time to zero, and starts measuring elapsed time.

Start

Starts, or resumes, measuring elapsed time for an interval.

StartNew

Initializes a new Stopwatch instance, sets the elapsed time property to zero, and starts measuring elapsed time.

Stop

Stops measuring elapsed time for an interval.

ToString

Returns a string that represents the current object. Inherited from Object.

Top

Fields
Show:
Name

Description

Frequency

Gets the frequency of the timer as the number of ticks per second. This field is readonly.

IsHighResolution

Indicates whether the timer is based on a highresolution performance counter. This field is readonly.

Inherited

Protected

Top

Remarks
A 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 Start method, then
eventually call the Stop method, and then you check elapsed time using the Elapsed property.
A Stopwatch instance is either running or stopped; use IsRunning to determine the current state of a Stopwatch. Use Start to begin measuring elapsed time; use Stop to stop measuring
elapsed time. Query the elapsed time value through the properties Elapsed, ElapsedMilliseconds, or ElapsedTicks. You can query the elapsed time properties while the instance is running
or stopped. The elapsed time properties steadily increase while the Stopwatch is running; they remain constant when the instance is stopped.
By default, the elapsed time value of a Stopwatch instance equals the total of all measured time intervals. Each call to Start begins counting at the cumulative elapsed time; each call to
Stop ends the current interval measurement and freezes the cumulative elapsed time value. Use the Reset method to clear the cumulative elapsed time in an existing Stopwatch instance.
The Stopwatch measures elapsed time by counting timer ticks in the underlying timer mechanism. If the installed hardware and operating system support a highresolution 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. Use the Frequency and
IsHighResolution fields to determine the precision and resolution of the Stopwatch timing implementation.
The Stopwatch class assists the manipulation of timingrelated performance counters within managed code. Specifically, the Frequency field and GetTimestamp method can be used in
place of the unmanaged Win32 APIs QueryPerformanceFrequency and QueryPerformanceCounter.
Note
On a multiprocessor computer, it does not matter which processor the thread runs on. However, because of bugs in the BIOS or the Hardware Abstraction Layer HAL, you can get
different timing results on different processors. To specify processor affinity for a thread, use the ProcessThread.ProcessorAffinity method.

Examples
The following example demonstrates how to use the Stopwatch class to determine the execution time for an application.
C#

usingSystem;
usingSystem.Diagnostics;
usingSystem.Threading;
classProgram
{
staticvoidMain(string[]args)
{
StopwatchstopWatch=newStopwatch();
stopWatch.Start();
Thread.Sleep(10000);
stopWatch.Stop();
//GettheelapsedtimeasaTimeSpanvalue.
TimeSpants=stopWatch.Elapsed;
//FormatanddisplaytheTimeSpanvalue.
stringelapsedTime=String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
ts.Hours,ts.Minutes,ts.Seconds,
ts.Milliseconds/10);
Console.WriteLine("RunTime"+elapsedTime);
}

The following example demonstrates the use of the Stopwatch class to calculate performance data.
C#

usingSystem;
usingSystem.Diagnostics;
namespaceStopWatchSample
{
classOperationsTimer
{
publicstaticvoidMain()
{
DisplayTimerProperties();
Console.WriteLine();
Console.WriteLine("PresstheEnterkeytobegin:");
Console.ReadLine();
Console.WriteLine();
TimeOperations();
}
publicstaticvoidDisplayTimerProperties()
{
//Displaythetimerfrequencyandresolution.
if(Stopwatch.IsHighResolution)
{
Console.WriteLine("Operationstimedusingthesystem'shighresolutionperformancecounter.");
}
else
{
Console.WriteLine("OperationstimedusingtheDateTimeclass.");
}
longfrequency=Stopwatch.Frequency;
Console.WriteLine("Timerfrequencyintickspersecond={0}",
frequency);
longnanosecPerTick=(1000L*1000L*1000L)/frequency;
Console.WriteLine("Timerisaccuratewithin{0}nanoseconds",
nanosecPerTick);
}
privatestaticvoidTimeOperations()
{
longnanosecPerTick=(1000L*1000L*1000L)/Stopwatch.Frequency;
constlongnumIterations=10000;
//Definetheoperationtitlenames.
String[]operationNames={"Operation:Int32.Parse(\"0\")",
"Operation:Int32.TryParse(\"0\")",
"Operation:Int32.Parse(\"a\")",
"Operation:Int32.TryParse(\"a\")"};

//Timefourdifferentimplementationsforparsing
//anintegerfromastring.
for(intoperation=0;operation<=3;operation++)
{
//Definevariablesforoperationstatistics.
longnumTicks=0;
longnumRollovers=0;
longmaxTicks=0;
longminTicks=Int64.MaxValue;
intindexFastest=1;
intindexSlowest=1;
longmilliSec=0;
Stopwatchtime10kOperations=Stopwatch.StartNew();
//Runthecurrentoperation10001times.
//Thefirstexecutiontimewillbetossed
//out,sinceitcanskewtheaveragetime.
for(inti=0;i<=numIterations;i++)
{
longticksThisTime=0;
intinputNum;
StopwatchtimePerParse;

switch(operation)
{
case0:
//Parseavalidintegerusing
//atrycatchstatement.
//Startanewstopwatchtimer.
timePerParse=Stopwatch.StartNew();
try
{
inputNum=Int32.Parse("0");
}
catch(FormatException)
{
inputNum=0;
}
//Stopthetimer,andsavethe
//elapsedticksfortheoperation.
timePerParse.Stop();
ticksThisTime=timePerParse.ElapsedTicks;
break;
case1:
//Parseavalidintegerusing
//theTryParsestatement.
//Startanewstopwatchtimer.
timePerParse=Stopwatch.StartNew();
if(!Int32.TryParse("0",outinputNum))
{
inputNum=0;
}
//Stopthetimer,andsavethe
//elapsedticksfortheoperation.
timePerParse.Stop();
ticksThisTime=timePerParse.ElapsedTicks;
break;
case2:
//Parseaninvalidvalueusing
//atrycatchstatement.
//Startanewstopwatchtimer.
timePerParse=Stopwatch.StartNew();
try
{
inputNum=Int32.Parse("a");
}
catch(FormatException)
{
inputNum=0;
}
//Stopthetimer,andsavethe
//elapsedticksfortheoperation.
timePerParse.Stop();
ticksThisTime=timePerParse.ElapsedTicks;
break;
case3:
//Parseaninvalidvalueusing
//theTryParsestatement.
//Startanewstopwatchtimer.
timePerParse=Stopwatch.StartNew();
if(!Int32.TryParse("a",outinputNum))
{
inputNum=0;
}
//Stopthetimer,andsavethe
//elapsedticksfortheoperation.
timePerParse.Stop();
ticksThisTime=timePerParse.ElapsedTicks;
break;
default:
break;
}
//Skipoverthetimeforthefirstoperation,

//justincaseitcausedaonetime
//performancehit.
if(i==0)
{
time10kOperations.Reset();
time10kOperations.Start();
}
else
{
//Updateoperationstatistics
//foriterations110001.
if(maxTicks<ticksThisTime)
{
indexSlowest=i;
maxTicks=ticksThisTime;
}
if(minTicks>ticksThisTime)
{
indexFastest=i;
minTicks=ticksThisTime;
}
numTicks+=ticksThisTime;
if(numTicks<ticksThisTime)
{
//Keeptrackofrollovers.
numRollovers++;
}
}
}
//Displaythestatisticsfor10000iterations.
time10kOperations.Stop();
milliSec=time10kOperations.ElapsedMilliseconds;
Console.WriteLine();
Console.WriteLine("{0}Summary:",operationNames[operation]);
Console.WriteLine("Slowesttime:#{0}/{1}={2}ticks",
indexSlowest,numIterations,maxTicks);
Console.WriteLine("Fastesttime:#{0}/{1}={2}ticks",
indexFastest,numIterations,minTicks);
Console.WriteLine("Averagetime:{0}ticks={1}nanoseconds",
numTicks/numIterations,
(numTicks*nanosecPerTick)/numIterations);
Console.WriteLine("Totaltimeloopingthrough{0}operations:{1}milliseconds",
numIterations,milliSec);
}
}
}
}

Version Information
.NET Framework
Supported in: 4, 3.5, 3.0, 2.0

.NET Framework Client Profile


Supported in: 4, 3.5 SP1

Platforms
Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 Server Core not supported, Windows Server 2008 R2 Server Core
supported with SP1 or later, Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Thread Safety
Any public static Shared in Visual Basic members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also
Reference

System.Diagnostics Namespace
TimeSpan

Community Additions

Error in second example


The nanosecPerTick fields in the example should really be a double precision number since when I run the program, the stopwatch frequency is 334 picoseconds and nanosecPerTick just gets evaluated to
0.
Toberon
5/7/2011

Simple benchmark program


Create a C# Windows Forms Application project with a Button and a RichTextBox and add this code:

privatevoidbutton1_Click(objectsender,EventArgse)
{
intrepeat=10;
List<double>result=newList<double>();
stringresultAll=string.Empty;
for(inti=0;i<=repeat;i++)
{
Stopwatchsw=newStopwatch();
sw.Start();
stringstr="abcdefghijklmnopqrstuvwxyz";
str=str.Replace("","");
sw.Stop();
doubletime=sw.Elapsed.TotalMilliseconds;
result.Add(time);
}
result.RemoveAt(0);
doubleresultAverage=result.Sum()/(repeat1);
foreach(doubleiteminresult)
{
resultAll+=item.ToString()+"ms\n";
}
richTextBox1.Text="Average:\n"+resultAverage+"ms\n\nAll:\n"+resultAll;
}

For the Stopwatch to work, you also need to add this code:

usingSystem.Diagnostics;

Press F5 and click on the button. A text similar to the one right below should appear in the textbox.

Average: 0,00376666666666667 ms

All:
0,0037 ms
0,0034 ms
0,003 ms
0,0034 ms
0,0034 ms
0,0034 ms
0,0034 ms
0,0034 ms
0,0034 ms
0,0034 ms

Comments
Line 3: You can change the number of repetitions to 100 or 1000 or whatever you like.

Line 1011: The code to benchmark. Change these lines to whatever you like.

Line 16: Because the first repetion seems to take significantly longer time to execute than the other repetions, I think it's a good idea to remove it before the average time is calculated.

matsolof
2/1/2011

2014 Microsoft

Potrebbero piacerti anche