disruptive
disruptive

Reputation: 5946

Measuring Clock Cycles C#

I'm trying to benchmark a series of algorithms by using the C# StopWatch function, using:

var timer = Stopwatch.StartNew();
// Do something
timer.Stop();
var elapsed2 = timer.ElapsedTicks;
Console.WriteLine(elapsed2);

My question is what these ticks actually relate to. I.e. are these clock cycles. I know I can get the Frequency from Stopwatch.Frequency, but is this actually the same as clock cycles. I.e. a tick count of 553534 corresponds to as many CPU cycles.

Upvotes: 0

Views: 1585

Answers (2)

Guffa
Guffa

Reputation: 700342

That depends on the capabilities of the system.

The IsHighResolution field can tell you how the Stopwatch class tells time. If it is true, then it uses the performance counter, and the ticks might be clock cycles. What they actually represent is dependent on the harware.

Upvotes: 3

StriplingWarrior
StriplingWarrior

Reputation: 156524

From the docs

Note
Stopwatch ticks are different from DateTime.Ticks. Each tick in the DateTime.Ticks value represents one 100-nanosecond interval. Each tick in the ElapsedTicks value represents the time interval equal to 1 second divided by the Frequency.

Frequency:

The timer frequency indicates the timer precision and resolution. For example, a timer frequency of 2 million ticks per second equals a timer resolution of 500 nanoseconds per tick. In other words, because one second equals 1 billion nanoseconds, a timer frequency of 2 million ticks per second is equivalent to 2 million ticks per 1 billion nanoseconds, which can be further simplified to 1 tick per 500 nanoseconds.

The Frequency value depends on the resolution of the underlying timing mechanism. If the installed hardware and operating system support a high-resolution performance counter, then the Frequency value reflects the frequency of that counter. Otherwise, the Frequency value is based on the system timer frequency.

Because the Stopwatch frequency depends on the installed hardware and operating system, the Frequency value remains constant while the system is running.

Upvotes: 4

Related Questions