Wojciech Kmita
Wojciech Kmita

Reputation: 259

Is there an easy way to retrieve the start time stamp from TimeSpan

What is the difference between the TimeSpan private field startTimeStamp and the DateTime.Ticks property? Is there an easy way to retrieve the startTimeStamp (without using reflection) ?

enter image description here

Upvotes: 1

Views: 1158

Answers (3)

Irfan
Irfan

Reputation: 2771

You can merely estimate the start time stamp. All you have to do is to call GetTimeStamp() just after starting StopWatch.

System.Diagnostics.Stopwatch watch = new Stopwatch();
watch.Start();
long ts = Stopwatch.GetTimestamp();

enter image description here

and

ts => 62583777603

Upvotes: 1

Samuel Neff
Samuel Neff

Reputation: 74899

startTimeStamp is a long, it's not a TimeSpan and it's not necessarily DateTime.Ticks.

It will be the time the StopWatch was started, which will be the time based on a high performance counter, or DateTime.Ticks if no high performance counter is available.

You can get the current value for what startTimeStamp is generated from by calling Stopwatch.GetTimeStamp() static method.

The startTimeStamp is not directly exposed but you can calculate it by calling

Stopwatch.GetTimeStamp() - stopwatch.GetRawElapsedTicks() 

Upvotes: 5

SLaks
SLaks

Reputation: 887285

Here is the source of the method used to initialize that field:

    public static long GetTimestamp() {
        if(IsHighResolution) { 
            long timestamp = 0;
            SafeNativeMethods.QueryPerformanceCounter(out timestamp);
            return timestamp;
        } 
        else {
            return DateTime.UtcNow.Ticks; 
        } 
    }

    [DllImport(ExternDll.Kernel32)]
    [ResourceExposure(ResourceScope.None)]
    public static extern bool QueryPerformanceCounter(out long value); 

Since this method is public, you can also call it yourself.

Upvotes: 2

Related Questions