Michael IV
Michael IV

Reputation: 11506

Get elapsed time since application start

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.

Upvotes: 31

Views: 44158

Answers (2)

SubSpecs
SubSpecs

Reputation: 57

public static class Runtime
{
    static Runtime() 
    {
        var ThisProcess = System.Diagnostics.Process.GetCurrentProcess(); LastSystemTime = (long)(System.DateTime.Now - ThisProcess.StartTime).TotalMilliseconds; ThisProcess.Dispose();
        StopWatch = new System.Diagnostics.Stopwatch(); StopWatch.Start();
    }
    private static long LastSystemTime;
    private static System.Diagnostics.Stopwatch StopWatch;

    //Public.
    public static long CurrentRuntime { get { return StopWatch.ElapsedMilliseconds + LastSystemTime; } }
}

Then call: Runtime.CurrentRuntime to get the current programs runtime in miliseconds.

Note: You can replace the TotalMilliseconds/ElapsedMilliseconds to any other time metric you need.

Upvotes: 1

spender
spender

Reputation: 120518

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.

Upvotes: 64

Related Questions