Click here to Skip to main content
15,890,527 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to be able to use my Windows clock's precision to the maximum and yet have efficiency in timestamping a lot of events coming in at a high rate of speed. Currently I am using DateTime.Now stored in an array, but I hear this is not the best way to do it. Would a stopwatch implementation be best? For example, instantiate a stopwatch beforehand and then store the elapsed time of the stopwatch rather than sampling DateTime.Nows?

Thank you oh coding Gods!! :)

A BIG thank you as always!

What I have tried:

some event going really really fast:
C#
{

TimeArray[x] = DateTime.Now;

}
Posted
Updated 26-Aug-22 19:22pm
v2
Comments
PIEBALDconsult 26-Aug-22 16:33pm    
I expect that DateTime.Now (or UtcNow) is better than a Stopwatch for that purpose.
I have found that Stopwatch is very poor for very short spans of time.
Admin BTA 26-Aug-22 16:35pm    
Thanks PIEBALD!
PIEBALDconsult 27-Aug-22 11:35am    
I'm now trying to imagine what events would be that frequent at the Boyce Thompson Arboretum.

1 solution

You could use Unix Timestamps:
C#
// Get the offset from current time in UTC time
DateTimeOffset dto = new DateTimeOffset(DateTime.UtcNow);

// Get the unix timestamp in seconds
string unixTime = dto.ToUnixTimeSeconds().ToString();

// Get the unix timestamp in seconds, and add the milliseconds
string unixTimeMilliSeconds = dto.ToUnixTimeMilliseconds().ToString();

Or you could use Epoch, commonly used in Web APIs:
C#
var epoch = DateTime2Epoch(DateTime.Now);

int DateTime2Epoch(DateTime dateTime)
{
    TimeSpan t = dateTime.ToUniversalTime() - new DateTime(1970, 1, 1);
    int secondsSinceEpoch = (int)t.TotalSeconds;
    return secondsSinceEpoch;
}

For higher precision, you could use:
C#
var ticks = DateTime.Now.Ticks
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900