2

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!

BrNi05
  • 57
  • 2
  • 6
  • `var elapsed = DateTime.Now - now;`, this produces a [TimeSpan](https://learn.microsoft.com/en-us/dotnet/api/system.timespan?view=net-5.0), and there is absolutely nothing to be concerned about, the passage of time is very efficient, it 'just happens'. – Peter B Feb 23 '21 at 12:48
  • Why all the concern about efficiency here? Are you just trying to be efficient, or is there some particular need you're trying to optimize for? – mason Feb 23 '21 at 13:53
  • 2
    StopWatch : https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.stopwatch?view=net-5.0. – granadaCoder Feb 23 '21 at 14:06
  • This is probably a borderline repeat question. https://stackoverflow.com/questions/55686928/using-stopwatch-in-c-sharp – granadaCoder Feb 23 '21 at 14:07

2 Answers2

1

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;
trashr0x
  • 6,457
  • 2
  • 29
  • 39
0

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.

PMF
  • 14,535
  • 3
  • 23
  • 49