i want a real time clock with precision of microseconds how can i do so?
is there any real time clock other than stopwatch;
You want System.Diagnostics.Stopwatch, which can measure time intervals accurately to the microsecond (depending on hardware limitations).
System.Diagnostics.Stopwatch uses the QueryPerformanceCounter and QueryPerformanceFrequency Windows APIs. The resolution is not standard across machines, but generally it's on the order of microseconds (see this KB article for more info).
In Vista/Win7 there is also QueryProcessCycleTime and QueryThreadCycleTime which will give you the number of elapsed cycles for your process/thread. This is useful if you want to know only the active time for the process (e.g. time when you weren't switched-out).
The most precise timer available in .NET is StopWatch.
For a high resolution measurements you could use the QueryPerformanceCounter function:
class Program
{
[DllImport("kernel32.dll")]
private static extern void QueryPerformanceCounter(ref long ticks);
static void Main()
{
long startTicks = 0L;
QueryPerformanceCounter(ref startTicks);
// some task
long endTicks = 0L;
QueryPerformanceCounter(ref endTicks);
long res = endTicks - startTicks;
}
}
check this http://www.c-sharpcorner.com/UploadFile/kapilsoni88/Digital_Click08142008142713PM/Digital_Click.aspx
and also check this http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx
If you want a good time mesurement I think csharp as an high level language might not be a good idea. you could assemble a simple program that taps to RTC and then tie it to your program via a library. That is literally the best possible scenario you can get whith no Object overhang, but it requires some low level know how to put together.
If you have no internet access and you want real time for timed trial license of software then you can use USB dongle with Real time clock.
Its time calculation is driven by an internal clock which is battery-driven. You can access the time from USB dongle using API functions which come along with these types of dongles.
EX-http://www.senselock-europe.com/en/elite-el-rtc-dongle.html
Related
I just ran into some unexpected behavior with DateTime.UtcNow while doing some unit tests. It appears that when you call DateTime.Now/UtcNow in rapid succession, it seems to give you back the same value for a longer-than-expected interval of time, rather than capturing more precise millisecond increments.
I know there is a Stopwatch class that would be better suited for doing precise time measurements, but I was curious if someone could explain this behavior in DateTime? Is there an official precision documented for DateTime.Now (for example, precise to within 50 ms?)? Why would DateTime.Now be made less precise than what most CPU clocks could handle? Maybe it's just designed for the lowest common denominator CPU?
public static void Main(string[] args)
{
var stopwatch = new Stopwatch();
stopwatch.Start();
for (int i=0; i<1000; i++)
{
var now = DateTime.Now;
Console.WriteLine(string.Format(
"Ticks: {0}\tMilliseconds: {1}", now.Ticks, now.Millisecond));
}
stopwatch.Stop();
Console.WriteLine("Stopwatch.ElapsedMilliseconds: {0}",
stopwatch.ElapsedMilliseconds);
Console.ReadLine();
}
Why would DateTime.Now be made less precise than what most CPU clocks could handle?
A good clock should be both precise and accurate; those are different. As the old joke goes, a stopped clock is exactly accurate twice a day, a clock a minute slow is never accurate at any time. But the clock a minute slow is always precise to the nearest minute, whereas a stopped clock has no useful precision at all.
Why should the DateTime be precise to, say a microsecond when it cannot possibly be accurate to the microsecond? Most people do not have any source for official time signals that are accurate to the microsecond. Therefore giving six digits after the decimal place of precision, the last five of which are garbage would be lying.
Remember, the purpose of DateTime is to represent a date and time. High-precision timings is not at all the purpose of DateTime; as you note, that's the purpose of StopWatch. The purpose of DateTime is to represent a date and time for purposes like displaying the current time to the user, computing the number of days until next Tuesday, and so on.
In short, "what time is it?" and "how long did that take?" are completely different questions; don't use a tool designed to answer one question to answer the other.
Thanks for the question; this will make a good blog article! :-)
DateTime's precision is somewhat specific to the system it's being run on. The precision is related to the speed of a context switch, which tends to be around 15 or 16 ms. (On my system, it is actually about 14 ms from my testing, but I've seen some laptops where it's closer to 35-40 ms accuracy.)
Peter Bromberg wrote an article on high precision code timing in C#, which discusses this.
I would like a precise Datetime.Now :), so I cooked this up:
public class PreciseDatetime
{
// using DateTime.Now resulted in many many log events with the same timestamp.
// use static variables in case there are many instances of this class in use in the same program
// (that way they will all be in sync)
private static readonly Stopwatch myStopwatch = new Stopwatch();
private static System.DateTime myStopwatchStartTime;
static PreciseDatetime()
{
Reset();
try
{
// In case the system clock gets updated
SystemEvents.TimeChanged += SystemEvents_TimeChanged;
}
catch (Exception)
{
}
}
static void SystemEvents_TimeChanged(object sender, EventArgs e)
{
Reset();
}
// SystemEvents.TimeChanged can be slow to fire (3 secs), so allow forcing of reset
static public void Reset()
{
myStopwatchStartTime = System.DateTime.Now;
myStopwatch.Restart();
}
public System.DateTime Now { get { return myStopwatchStartTime.Add(myStopwatch.Elapsed); } }
}
From MSDN you'll find that DateTime.Now has an approximate resolution of 10 milliseconds on all NT operating systems.
The actual precision is hardware dependent. Better precision can be obtained using QueryPerformanceCounter.
For what it's worth, short of actually checking the .NET source, Eric Lippert provided a comment on this SO question saying that DateTime is only accurate to approx 30 ms. The reasoning for not being nanosecond accurate, in his words, is that it "doesn't need to be."
From MSDN documentation:
The resolution of this property
depends on the system timer.
They also claim that the approximate resolution on Windows NT 3.5 and later is 10 ms :)
The resolution of this property depends on the system timer, which
depends on the underlying operating system. It tends to be between 0.5
and 15 milliseconds.
As a result, repeated calls to the Now property in a short time interval, such as in a loop, may return the same value.
MSDN Link
A just need a stable count of the current program's progression in milliseconds in C#. I don't care about what timestamp it goes off of, whether it's when the program starts, midnight, or the epoch, I just need a single function that returns a stable millisecond value that does not change in an abnormal manner besides increasing by 1 each millisecond. You'd be surprised how few comprehensive and simple answers I could find by searching.
Edit: Why did you remove the C# from my title? I'd figure that's a pretty important piece of information.
When your program starts create a StopWatch and Start() it.
private StopWatch sw = new StopWatch();
public void StartMethod()
{
sw.Start();
}
At any point you can query the Stopwatch:
public void SomeMethod()
{
var a = sw.ElapsedMilliseconds;
}
If you want something accurate/precise then you need to use a StopWatch, and please read Eric Lippert's Blog (formerly the Principal Developer of the C# compiler Team) Precision and accuracy of DateTime.
Excerpt:
Now, the question “how much time has elapsed from start to finish?” is a completely different question than “what time is it right now?” If the question you want to ask is about how long some operation took, and you want a high-precision, high-accuracy answer, then use the StopWatch class. It really does have nanosecond precision and accuracy that is close to its precision.
If you don't need an accurate time, and you don't care about precision and the possibility of edge-cases that cause your milliseconds to actually be negative then use DateTime.
Do you mean DateTime.Now? It holds absolute time, and subtracting two DateTime instances gives you a TimeSpan object which has a TotalMilliseconds property.
You could store the current time in milliseconds when the program starts, then in your function get the current time again and subtract
edit:
if what your going for is a stable count of process cycles, I would use processor clocks instead of time.
as per your comment you can use DateTime.Ticks, which is 1/10,000 of a millisecond per tick
Also, if you wanted to do the time thing you can use DateTime.Now as your variable you store when you start your program, and do another DateTime.Now whenever you want the time. It has a millisecond property.
Either way DateTime is what your looking for
It sounds like you are just trying to get the current date and time, in milliseconds. If you are just trying to get the current time, in milliseconds, try this:
long milliseconds = DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond;
This is a bit of an academic question as I'm struggling with the thinking behind Microsoft using double as the data type for the Interval property!
Firstly from MDSN Interval is the time, in milliseconds, between Elapsed events; I would interpret that to be a discrete number so why the use of a double? surely int or long makes greater sense!?
Can Interval support values like 5.768585 (5.768585 ms)? Especially when one considers System.Timers.Timer to have nowhere near sub millisecond accuracy... Most accurate timer in .NET?
Seems a bit daft to me.. Maybe I'm missing something!
Disassembling shows that the interval is consumed via a call to (int)Math.Ceiling(this.interval) so even if you were to specify a real number, it would be turned into an int before use. This happens in a method called UpdateTimer.
Why? No idea, perhaps the spec said that double was required at one point and that changed? The end result is that double is not strictly required, because it is eventually converted to an int and cannot be larger than Int32.MaxValue according to the docs anyway.
Yes, the timer can "support" real numbers, it just doesn't tell you that it silently changed them. You can initialise and run the timer with 100.5d, it turns it into 101.
And yes, it is all a bit daft: 4 wasted bytes, potential implicit casting, conversion calls, explicit casting, all needless if they'd just used int.
The reason to use a double here is the attempt to provide enough accuracy.
In detail: The systems interrupt time slices are given by ActualResolution which is returned by NtQueryTimerResolution(). NtQueryTimerResolution is exported by the native Windows NT library NTDLL.DLL. The System time increments are given by TimeIncrement which is returned by GetSystemTimeAdjustment().
These two values are determining the behavior of the system timers. They are integer values and the express 100 ns units. However, this is already insufficient for certain hardware today. On some systems ActualResolution is returned 9766 which would correspond to 0.9766 ms. But in fact these systems are operating at 1024 interrupts per second (tuned by proper setting of the multimedia interface). 1024 interrupts a second will cause the interrupt period to be 0.9765625 ms. This is of too high detail, it reaches into the 100 ps regime and can therefore not be hold in the standard ActualResolution format.
Therefore it has been decided to put such time-parameters into double. But: This does not mean that all of the posible values are supported/used. The granularity given by TimeIncrement will persist, no matter what.
When dealing with timers it is always advisable to look at the granularity of the parameters involved.
So back to your question: Can Interval support values like 5.768585 (ms) ?
No, the system I've taken as an example above cannot.
But it can support 5.859375 (ms)!
Other systems with different hardware may support other numbers.
So the idea of introducing a double here is not such a stupid idea and actually makes sense. Spending another 4 bytes to get things finally right is a good investment.
I've summarized some more details about Windows time matters here.
From this article http://blogs.msdn.com/b/ericlippert/archive/2010/04/08/precision-and-accuracy-of-datetime.aspx:
Now, the question “how much time has elapsed from start to finish?” is a completely different question than “what time is it right now?” If the question you want to ask is about how long some operation took, and you want a high-precision, high-accuracy answer, then use the StopWatch class. It really does have nanosecond precision and accuracy that is close to its precision.
The question is - what should I use if I need elapsed time from start to finish and I need 20 ms precision?
StopWatch has much better precision so I'm afraid that I will pay processor time for "extra-precision" which I don't need.
DateTime.Now has exactly precision I need but it also has a lot of extra-stuff like Month, Year etc. and I'm again afraid that this makes it much slower.
This article should help you:
http://www.dijksterhuis.org/timing-function-performance-stopwatch-class/
In general it says that the Stopwatch is the better choice, which is even my personal opinion.
The only (considerable?) overhead of the StopWatch is the incorporation of QueryPerformanceFrequency determining if the StopWatch will go on with high resolution frequency or not. Actually it is an overhead only if it will go without high resolution frequency. Otherwise is a faster option as it gets the timestamp with a WIN32 QueryPerformanceCounter call instead of DateTime.UtcNow.Ticks.
From what I read on the internet untill now StopWatch class from System.Diagnostics namespace is the best class used for timing.
If you want precision under 1 ms remember to use the Elapsed.TotalMilliseconds property to retrieve elapsed time, sw.ElapsedMilliseconds jumps in increments of 1 ms.
using System;
using System.Diagnostics;
namespace MySolution
{
class Program
{
static void Main(string[] args)
{
var sw = Stopwatch.StartNew();
// code to be timed here
sw.Stop();
Console.WriteLine("Run time in ms = {0}", sw.Elapsed.TotalMilliseconds);
}
}
}
i'd like to switch bit with time shorter than 1 ms. I'd prefer do this in C# Windows Forms, but it can be in for example console app in C++, C#. What i want to do is to switch bit and send it via LPT port.
Switching bit in this code is to slow..
PortAccess.Output(888,1);
Thread.Sleep(1);
PortAccess.Output(888,0);
Thread.Sleep(1);
I've read this post: How to use QueryPerformanceCounter? , but it's only timer..
Please help :)
There is no easy or obvious way to do this kind of fine-grained timing control in the C#/.NET environment. You can use the Stopwatch class to get close, but the resolution isn't great for real-time work. To use a timer to do something like this - nonsense code but you loop until the time elapsed is your desired interval:
Stopwatch swatch = new Stopwatch();
while(true)
{
swatch.Reset();
swatch.Start();
PortAccess.Output(888, 1);
while (swatch.ElapsedMilliseconds < 1) { }
swatch.Stop();
swatch.Reset();
swatch.Start();
PortAccess.Output(888, 0);
while (swatch.ElapsedMilliseconds < 1) { }
swatch.Stop();
}
Sleep should not be used for timing anywhere. Sleep only basically says, "sleep for at least X milliseconds". So Sleep(1) might sleep for 25ms.
And a by-the-way: next to no PCs have parallel ports anymore. This is an ancient - no, the most ancient way to write bits or flip outputs external to a PC. Doing it by directly outputting to a PC IO port is really rubbish too. You could look for an external digital IO device/board/interface with a decent driver - much better idea.
First, you have to be aware that Sleep() does not have such a fine resolution. Usually it's about 20ms resolution, so that your calls will wait much longer than what you want.
Second, in a system like Windows which is not providing realtime warranties you cannot rely on being able to actually perform something each millisecond, even if you keep the thread alive (using Spinwait() for instance). The thread may and will still be interrupted by the OS in the normal task switching process and therefore you'll have periods of no activity for up to several milliseconds.
In short, don't try that. It will not work.
Keeping in mind that what Lucero and Kieren, I'll still answer your question.
You can use the Stopwatch to get sub-millisecond precision using Ticks where 1 Tick== 1/10,000 millisecond. For example here wait 1/10 millisecond:
Stopwatch sw = Stopwatch.StartNew();
while (sw.ElapsedTicks <1000);
Debug.Print(sw.ElapsedTicks.ToString());
You should make sure that Stopwatch has a high enough frequency for your needs on the system you'll be using it. Also, please remember that you are not at the driver level here, so there is nothing approaching real-time guarantees with this.