Get time in milliseconds using C# - c#

I'm making a program in which I need to get the time in milliseconds. By time, I mean a number that is never equal to itself, and is always 1000 numbers bigger than it was a second ago. I've tried converting DateTime.Now to a TimeSpan and getting the TotalMilliseconds from that... but I've heard it isn't perfectly accurate.
Is there an easier way to do this?

long milliseconds = DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond;
This is actually how the various Unix conversion methods are implemented in the DateTimeOffset class (.NET Framework 4.6+, .NET Standard 1.3+):
long milliseconds = DateTimeOffset.Now.ToUnixTimeMilliseconds();

Use the Stopwatch class.
Provides a set of methods and
properties that you can use to
accurately measure elapsed time.
There is some good info on implementing it here:
Performance Tests: Precise Run Time Measurements with System.Diagnostics.Stopwatch

The DateTime.Ticks property gets the number of ticks that represent the date and time.
10,000 Ticks is a millisecond (10,000,000 ticks per second).

I use the following class. I found it on the Internet once, postulated to be the best NOW().
/// <summary>Class to get current timestamp with enough precision</summary>
static class CurrentMillis
{
private static readonly DateTime Jan1St1970 = new DateTime (1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
/// <summary>Get extra long current timestamp</summary>
public static long Millis { get { return (long)((DateTime.UtcNow - Jan1St1970).TotalMilliseconds); } }
}
Source unknown.

You can try the QueryPerformanceCounter native method. See http://www.pinvoke.net/default.aspx/kernel32/QueryPerformanceCounter.html for more information. This is what the Stopwatch class uses.
See How to get timestamp of tick precision in .NET / C#? for more information.
Stopwatch.GetTimestamp() gives access to this method:
public static long GetTimestamp() {
if(IsHighResolution) {
long timestamp = 0;
SafeNativeMethods.QueryPerformanceCounter(out timestamp);
return timestamp;
}
else {
return DateTime.UtcNow.Ticks;
}
}

I used DateTime.Now.TimeOfDay.TotalMilliseconds (for current day), hope it helps you out as well.

Use System.DateTime.Now.ToUniversalTime(). That puts your reading in a known reference-based millisecond format that totally eliminates day change, etc.

Using Stopwatch class we can achieve it from System.Diagnostics.
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
stopwatch.Stop();
Debug.WriteLine(stopwatch.ElapsedMilliseconds);

System.DateTimeOffset.Now.ToString("MM/dd/yyyy hh:mm:ss.fff tt") to get the millisecond in the format of '04/01/2021 04:32:14.788 PM'
https://learn.microsoft.com/en-us/dotnet/standard/base-types/how-to-display-milliseconds-in-date-and-time-values

As I understand your requirements Environment.TickCount fits the bill. It returns number of milliseconds since startup, so it always increases and can be used for computing elapsed time in milliseconds. If you want absolute time also, you can get current time and current Environment.TickCount, and compute new absolute time based on that and new Environment.TickCount.

Related

C# - most efficient way of measuring ellapsed time

I am working on a C# console application in which I need to know the ellapsed time since the program has started.
I have a variable that stores the time on start (DateTime now = DateTime.Now;)
What is the most efficient way of measuring the ellapsed time?
The ellapsed time can be hours - this is why I am concerned about efficiency and memory usage.
Thanks in advance!
Subtract the current time from the time the program started. This will return a TimeSpan which exposes properties like TotalHours which you can use to calculate the elapsed time.
// on start
var startTime = DateTime.UtcNow;
// later on, to see hours elapsed since then
var elapsed = (DateTime.UtcNow - startTime).TotalHours;
Don't worry. Measuring a time span does not use any resources, as it just compares now with then.
DateTime start = DateTime.Now;
// do some heavy calculation
TimeSpan delta = DateTime.Now - start; // get the time that elapsed
This does not use any resources except the variable for the start, which is just a 64 bit counter.
Note that for short timespans you're better off using Stopwatch, as this is not subject to time adjustments that may happen between start and now.

Why is time not incrementing

I am trying to show the timestamp of when a process begins and when it completes, but my time never increments (even though time in reality does)
DateTime now = DateTime.Now;
txt1.AppendText(now + Environment.NewLine);
//Lengthy process that usually takes 2 - 3 minutes
txt1.AppendText(now);
You are literally using the same variable with the same value as when you first displayed it. You would need to get the time again like this...
DateTime now = DateTime.Now;
txt1.AppendText(now + Environment.NewLine);
//Lengthy process that usually takes 2 - 3 minutes
DateTime timeHasPassed = DateTime.Now;
txt1.AppendText(timeHasPassed);
DateTime is a ValueType. When you assign it to a variable, you are making a copy of the value, not the reference.
This means that when you use DateTime.Now, you have to invoke it via the Get Property to get the latest time value.
txt1.AppendText(DateTime.Now + Environment.NewLine);
//Lengthy process that usually takes 2 - 3 minutes
txt1.AppendText(DateTime.Now);
That's because you captured and stored the DateTime.Now in a variable so it shows the stored value. Use DateTime.Now again instead of using now variable.
Don't use DateTime to measure your process time of your code.
You should never do any increment or math with DateTime.Now because it may be ambiguous due to DST and TimeZone issues.
Use StopWatch to measure elapsed time instead. This class offers high-precision timing in .NET. It is capable of measuring time with sensitivity of around 100s of nanoseconds.
You can use it's Start and Stop methods to control of a StopWatch object.

What is the default time precision of DateTime?

I did a small winform program for data transferring in Visual Studio, and I used a method to provide the transferring time duration. After the transferring being done, the program will return a dialog window to show the time.
But here I don't know what is the time precision or the resolution of the timer, how can it be such a precision, even micro second?
var startTime = DateTime.Now;
this.transferdata();
var endTime = DateTime.Now;
var timeElapsed = endTime.Subtract(startTime);
when I saw the definition of class DateTime, there is only a precision in milisecond. can anybody tell me why there is such a high resolution timer in the visual studio 2012? Or there is related to the operating system?
The precision of the clock depends on the operating system. The system clock ticks a certain number of times per second, and you can only measure whole ticks.
You can test the resolution for a specific computer using code like this:
DateTime t1 = DateTime.Now;
DateTime t2;
while ((t2 = DateTime.Now) == t1) ;
Console.WriteLine(t2 - t1);
On my computer the result is 00:00:00.0156253, which means that the system clock ticks 64 times per second.
(Note: The DateTime type also has ticks, but that is not the same as the system clock ticks. A DateTime tick is 1/10000000 second.)
To measure time more precisely, you should use the Stopwatch class. Its resolution also depends on the system, but is much higher than the system clock. You can get the resolution from the Stopwatch.Frequency property, and on my computer it returns 2143566 which is a tad more than 64...
Start a stopwatch before the work and stop it after, then get the elapsed time:
Stopwatch time = Stopwatch.StartNew();
this.transferdata();
time.Stop();
TimeSpan timeElapsed = time.Elapsed;
That will return the time in the resolution that the TimeSpan type can handle, e.g. 1/10000000 second. You can also calculate the time from the number of ticks:
double timeElapsed = (double)s.ElapsedTicks / (double)Stopwatch.Frequency;
You are confusing several things. Precision, Accuracy, Frequency, and Resolution.
You might have a variable that is accurate to a billion decimal places. But if you can't actually measure that small of a number then that's the difference between precision and resolution. Frequency is the number of times per second a measurement is taken, while relates to resolution. Accuracy is how closely a given sample is to the real measurement.
So, given that DateTime has a precision much higher than the system clock, simply saying DateTime.Now will not necessarily give you an exact timestamp. There are, however, Higher resolution timers in Windows, and the Stopwatch class uses them to measure time elapsed, so if you use this class you get a much better accuracy.
DateTime has no "default precision". It has only one precision, and that's the Minimum and Maximum values it can store. DateTime internally stores it's values as a single value, and this value is formatted to whatever type you want to display (seconds, minutes, days, ticks, whatever...).

Difference between ElapsedTicks, ElapsedMilliseconds, Elapsed.Milliseconds and Elapsed.TotalMilliseconds? (C#)

I'm totally confused between these 4. What is the difference between ElapsedMilliseconds (long), ElapsedTicks (long), Elapsed.TotalMilliseconds (double) and Elapsed.Milliseconds (int)?
I have a function
{
Stopwatch sw = new Stopwatch();
sw.Start();
MyTimeConsumingAction();
sw.Stop();
sw.//what?
}
How do I get the correct time consumed by my long running process from elapsed property of Stopwatch object in milliseconds?
Edit: I tried msdn documentation but it isn't anything detailed there..
Elapsed.TotalMilliseconds (double) returns the total number of whole and fractional milliseconds elapsed since inception
e.g. a stopwatch stopped at 1.23456 seconds would return 1234.56 in this property. See TimeSpan.TotalMilliseconds on MSDN
Elapsed.Milliseconds (int) returns the number of whole milliseconds in the current second
e.g. a stopwatch at 1.234 seconds would return 234 in this property. See TimeSpan.Milliseconds
ElapsedTicks (long) returns the ticks since start of the stopwatch.
In the context of the original question, pertaining to the Stopwatch class, ElapsedTicks is the number of ticks elapsed. Ticks occur at the rate of Stopwatch.Frequency, so, to compute seconds elapsed, calculate: numSeconds = stopwatch.ElapsedTicks / Stopwatch.Frequency.
The old answer defined ticks as the number of 100 nanosecond periods, which is correct in the context of the DateTime class, but not correct in the context of the Stopwatch class. See Stopwatch.ElapsedTicks on MSDN.
ElapsedMilliseconds returns a rounded number to the nearest full millisecond, so this might lack precision Elapsed.TotalMilliseconds property can give.
Elapsed.TotalMilliseconds is a double that can return execution times to the partial millisecond while ElapsedMilliseconds is Int64. e.g. a stopwatch at 0.0007 milliseconds would return 0, or 1234.56 milliseconds would return 1234 in this property. So for precision always use Elapsed.TotalMilliseconds.
See Stopwatch.ElapsedMilliseconds on MSDN for clarification.
Reflecting the Stopwatch class reveals that ElapsedMilliseconds is Elapsed ticks converted (and rounded) to milliseconds:
public TimeSpan Elapsed
{
get
{
return new TimeSpan(this.GetElapsedDateTimeTicks());
}
}
public long ElapsedMilliseconds
{
get
{
return this.GetElapsedDateTimeTicks() / 10000L;
}
}
in a short explanation from msdn:
ElapsedMilliseconds
This property represents elapsed time rounded down to the nearest whole millisecond value. For higher precision measurements, use the Elapsed or ElapsedTicks properties.
ElapsedTicks
This property represents the number of elapsed ticks in the underlying timer mechanism. A tick is the smallest unit of time that the Stopwatch timer can measure. Use the Frequency field to convert the ElapsedTicks value into a number of seconds.
Elapsed
Use the Elapsed property to retrieve the elapsed time value using TimeSpan methods and properties. For example, you can format the returned TimeSpan instance into a text representation, or pass it to another class that requires a TimeSpan parameter.
Elapsed is TimeSpan. If you want to display time, then just Elapsed.ToString() should do that

Get Ticks per second and convert to String value?

How do I get number of ticks per second of DateTime.UtcNow and convert it to a String value?
BAD QUESTION: try again Get ten millionths of a second
A particular value of DateTime doesn't have a "ticks per second" associated with it; ticks are ticks no matter which DateTime they're in. Ticks are 100 nanoseconds long, so there are 10,000,000 of them per second.
Now to get that as a string is as simple as the string literal "10000000"... although in general you would obtain a number and just call ToString() on it. For instance, you could use:
string ticksPerSecond = TimeSpan.TicksPerSecond.ToString();
Your question is a slightly odd one, so I wonder whether we're missing something... could you edit the question with more details about what you're trying to do. For example, are you trying to determine the number of ticks within the particular second of a particular DateTime? That's most easily done as:
long ticks = dt.Ticks % TimeSpan.TicksPerSecond;
You find the ticks per second as a constant on TimeSpan:
TimeSpan.TicksPerSecond
Not sure what you are trying to do though...
(DateTime.UtcNow.Ticks / TimeSpan.TicksPerSecond).ToString() // Total number of seconds...
I think you may want TimeSpan.TicksPerSecond.
Console.WriteLine("tps = {0}", TimeSpan.TicksPerSecond.ToString());
The number of ticks per second in a DateTime value is always 10000000. One tick is 100 nanoseconds.
So, if you want to convert that to a string:
10000000.ToString()

Categories

Resources