Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using c# System.DateTime like c++ time_t

Tags:

c#

datetime

time

In C++ I am able to get the current time when my application starts I can use

time_t appStartTime = time(null);

then to find the difference in seconds from when it started I can just do the same thing, then find the difference. It looks like I should be using "System.DateTime" in C# net, but the MSDN is confusing in its explanation.

How can I use System.DateTime to find the difference in time (in seconds) between when my application starts, and the current time?

like image 203
David Boland Avatar asked Dec 15 '25 13:12

David Boland


2 Answers

Use Now property

DateTime startTime = DateTime.Now;

//work

DateTime currentTime = DateTime.Now;

and then just simply calculate the difference.

currentTime - startTime;

If you would like to measure the performance consider using Stopwatch.

    Stopwatch stopWatch = new Stopwatch();
    stopWatch.Start();

    //work

    stopWatch.Stop();
like image 93
Lukasz Madon Avatar answered Dec 17 '25 03:12

Lukasz Madon


As everyone suggested... But they were a little wrong :-) Use DateTime.UtcNow, because

  • It's faster (DateTime.Now calls DateTime.UtcNow)
  • It works around change of DST on/off.

OR

As @Shekhar_Pro suggested (yes, he was right!), use the Stopwatch

var sw = Stopwatch.StartNew()
.... your code
sw.Stop();
var ms = sw.ElapsedMilliseconds;

or

var ticks = sw.ElapsedTicks;

Oh... and I was forgetting... What you are doing is probably worthless in certain situation... You know, 2011 processors are multicore (and even 2010 :-) )... If you app is vaguely multithread you are probably better measuring:

Process.GetCurrentProcess().TotalProcessorTime

This include the use of all the cores used by your app... So on a dual core, using both cores, it will "gain" 2 seconds for every "real time" second.

like image 26
xanatos Avatar answered Dec 17 '25 05:12

xanatos