Get elapsed time since application start
36,660
Process.GetCurrentProcess().StartTime
is your friend.
..so to get elapsed time since start:
DateTime.UtcNow - Process.GetCurrentProcess().StartTime.ToUniversalTime()
alternatively, if you need more definition, System.Diagnostics.Stopwatch
might be preferable. If so, start a stopwatch when your app starts:
Stopwatch sw = Stopwatch.StartNew();
then query the sw.Elapsed
property during your execution run.
Related videos on Youtube
Comments
-
Michael IV almost 2 years
I am porting an app from ActionScript3.0 (Flex) to C# (WPF).AS3.0 has got a handy utility called getTimer() which returns time since Flash Virtual machine start in milliseconds.I was searching in C# through classes as
DateTime DispatcherTimer System.Diagnostics.Process System.Diagnostics.Stopwatch
but found nothing like this.It seems a very basic feature to me.For example Unity3D which runs on Mono has something familiar. Do I miss some utility here?
Thanks in advance.
-
as-cii about 12 yearsWhether to choose one or the other is not a matter of precision but of needs instead.
Process.GetCurrentProcess().StartTime
will never be called at the same time ofStopwatch.StartNew()
! So it depends on when the user want to start timing. :) -
Michael IV about 12 yearsAre you sure Process.GetCurrentProcess returns time since the Application starts up? I just made a check: (DateTime.Now -Process.GetCurrentProcess().StartTime).TotalSeconds .At the moment the App is up I print the time to Console.It starts from 16-17 seconds.It is obviously too much because it took maximum 4 seconds for the App to start.
-
spender about 12 yearsInteresting. The docs seem to agree with me. If this really is the case, I'd say it merits a new question.
-
JJS about 10 years@MichaelIV - the large amount of time is pretty easy to replicate. Press F5. To get a concistently small amount of time, use CTRL + F5 (Start without Debugging). F5 (Run with Debugger) runs inside a AssemblyName.vshost.exe which maybe have been running longer than when you first 'start' your debugging session. Try using Process.GetCurrentProcess().ProcessName at the stdart of the program.
-
Syaiful Nizam Yahya about 9 yearsProcess.GetCurrentProcess().StartTime doesnt work for me. Im not on Unity by the way. Stopwatch worked for me.
-
ina about 5 yearscan this be used for determining total time across all session or only current active session
-
Vincent over 4 yearsStopwatch is much more reliable, DateTime.UtcNow - Process.GetCurrentProcess().StartTime.ToUniversalTime() is not reliable, because user may modify system time.