C# - most efficient way of measuring ellapsed time

Viewed 178

I am working on a C# console application in which I need to know the ellapsed time since the program has started.
I have a variable that stores the time on start (DateTime now = DateTime.Now;)

What is the most efficient way of measuring the ellapsed time?
The ellapsed time can be hours - this is why I am concerned about efficiency and memory usage.

Thanks in advance!

2 Answers

Subtract the current time from the time the program started. This will return a TimeSpan which exposes properties like TotalHours which you can use to calculate the elapsed time.

// on start
var startTime = DateTime.UtcNow;

// later on, to see hours elapsed since then
var elapsed = (DateTime.UtcNow - startTime).TotalHours;

Don't worry. Measuring a time span does not use any resources, as it just compares now with then.

DateTime start = DateTime.Now;

// do some heavy calculation

TimeSpan delta = DateTime.Now - start; // get the time that elapsed

This does not use any resources except the variable for the start, which is just a 64 bit counter.

Note that for short timespans you're better off using Stopwatch, as this is not subject to time adjustments that may happen between start and now.

Related