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
Related
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...).
Is it possible to make timer interval to float in c#.
If yes then how?
The timer interval is a double
Type: System.Double
The time, in milliseconds, between Elapsed events. The value must be greater than zero, and less than or equal to Int32.MaxValue. The default is 100 milliseconds.
http://msdn.microsoft.com/en-us/library/system.timers.timer.interval.aspx
According to msdn DateTime precision is 10 ms. So t2-t1 precision in the example below is also 10 ms. However the returned value is "double" what is confusing.
DateTime t1 = DateTime.Now; // precision is 10 ms
....
DateTime t2 = DateTime.Now; // precision is 10 ms
... (t2-t1).TotalMilliseconds; // double (so precision is less than 1 ms???)
I expect int value because double value doesn't make sense when precision is 10 ms. I need to use resulted value in Thread.Sleep(). Should I just cast to int?
The precision of DateTime itself is down to the tick.
The granularity of DateTime.Now is typically 10 or 15ms - it's the granularity of the system clock. (That doesn't mean the clock is accurate to the nearest 10 or 15ms, mind you.) The subtraction operator on DateTime shouldn't know or care about that though - the result is just a TimeSpan which again has a precision to the tick level.
Just casting to int should be absolutely fine.
(You might want to read Eric Lippert's blog post on this, by the way.)
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.
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()