Windows ce microsecond timer
Viewed times. Improve this question. Microsecond timing on a non-realtime OS is a tough ask. Is there any particular reason you can't use the std::chrono libraries? Chrono ultimately calls through to the Windows APIs and Windows just is not built for precise timing.
Why do you need this in the first place? In some cases using FIFOs can eliminate the need for high precision timers Sometimes clock tics method is enough Show 2 more comments.
Active Oldest Votes. Improve this answer. Kieveli Kieveli Add a comment. Among other things, the object store contains a file system. Data in the object store is compressed this is an optional setting for an OEM , so that if you have a KB program called pager. Of course, without a page file there is no way to page anything out. But even without a paging file, the presence of paged memory support helps to optimize the use of physical memory. Code is discarded when memory is low and will be paged back in when needed.
While demand paging reduces memory usage, a page fault during a time-critical operation can create unwanted delays. Developers of time-critical systems want to avoid paging activity when a critical deadline must be met.
Windows CE has an alternative function, LoadDriver, which is the same as LoadLibrary, except that it guarantees that all pages are loaded and locked into memory.
I mentioned at the beginning of this article that Windows CE is a configurable operating system, and this applies to the virtual memory system as well. While you gain the benefit of avoiding delays caused by page loading, you also lose the benefits of demand paging.
In particular, every application and DLL including device drivers are loaded entirely into memory before they start running. The downside, then, is that startup times for both applications and device drivers increases a bit. Used judiciously, however, this feature could help remove the memory paging issue from the real-time performance equation.
Of course, Windows CE is also an embedded operating system. As such, executables can reside in ROM and, when uncompressed, such executables can execute in place. The second major improvement is in the area of thread scheduling.
Incidentally, thread scheduling improvements help interrupt handling, since an IST must be scheduled like any other thread. And, of course, thread scheduling is important because real-time system developers like the convenience of creating both multithreaded and multiprocess solutions. You don't want the scheduler to take too long to switch between threads, or it might cause your code to miss important deadlines. You also want to make sure that you have the features you need to implement your threads in the most efficient manner.
After I explain the nestable interrupts, I'll explain each of the six key improvements for thread scheduling: new thread priorities, the addition of support for setting thread quantum, improved handling of priority inversion, improved timer granularity, the addition of semaphores, and better support for critical sections. The new real-time functions in Windows CE 3. There are two drawbacks to this new design. Obviously, lower-priority ISRs run more slowly.
But then good system design is all about balancing finite resources between competing demands. The reason is that the system needs to save more state before calling individual ISRs, so the average start time of all ISRs suffer a bit.
The good news, though, is that while average start times increase slightly, maximum start times decrease, particularly for the highest-priority ISRs.
An important difference between Windows CE 3. On Windows CE 2. Instead, it is a run-to-completion thread. This is no longer true on Windows CE 3. And higher-priority threads always preempt lower-priority threads.
Run-to-completion support is still available on Windows CE 3. Processing time for these two functions is measured in milliseconds. The default value for this quantum is milliseconds, but a system developer can set the default value to any value except zero in the OEMInit function.
By contrast, the default thread scheduling value on earlier versions of Windows CE was 25 milliseconds. If the kernel detects a value of zero, the default of milliseconds is used instead. A value that is too low causes the system to spend too much time in the scheduler, while a value that is too high can cause unacceptable delays between the time when threads are scheduled. With Windows CE 3. The scheduler looks ahead only one level, and not the five in the previous example. The net effect is that the scheduler doesn't burn CPU cycles on poorly designed threads.
Instead, it keeps the road clear for those threads that are tuned to focus on their real work during time-critical operations. Incidentally, if you are new to programming in Win32, you might discover the SetTimer function and wonder whether it provides a good way to meet precise timing needs. This function, which has been around since the dawn of Windows, is heavily tied to the message-based user interface.
The timing provided by this function is more suitable for user interface issues such as performing a "Rebooting in 10 seconds" countdown than for the precise needs of real-time system development. While sleep has become more accurate, the architects of Windows CE have not forgotten about battery life. New additions to the OEM Adaptation Layer allow the system tick to be reprogrammed during idle periods.
This allows the system to stay in an idle state, conserving battery life for longer periods of time. Windows CE 3. A semaphore is roughly like a mutex with a count. Or a mutex is like a semaphore with a count of 1. Semaphores let you set a limit to the number of threads that have access to a particular resource.
This provides a safe way to use critical sections without having to worry that a thread will block during a time-critical operation. Event Tracking enables an OEM to monitor the system's state to determine how well an application is running. The data enables OEMs to spot potential deadlocks and to detect priority inversion cases. Skip to main content. This browser is no longer supported. Download Microsoft Edge More info. Contents Exit focus mode. This article may contain URLs that were valid when originally published, but now link to sites or pages that no longer exist.
To maintain the flow of the article, we've left these URLs in the text, but disabled the links. In this article. Download the code for this article: Yao In Windows CE 3. This article looks at specific support for the creation of real-time systems and how it compares to the support in Windows for the desktop.
The way interrupt handlers, processes, memory management, and synchronization work in Windows CE 3. An extensive look at threads and thread priority, misconceptions surrounding them, and their impact on performance is included. Refinements to the Windows CE scheduler and support for nestable interrupts are also covered. What Windows CE provides, then, is a small, yet feature-rich, operating system. This sounds paradoxical. How can an operating system be both small and rich in features?
The answer is that Windows CE is highly configurable. The recently released Windows CE 3. It adds support for nestable interrupts, more thread priority levels, and refinements to the Windows CE scheduler.
Developers now have total control over system scheduling, with a wide range of features that help support the creation of real-time systems. Of course, the mere presence of great real-time support in the operating system doesn't guarantee that every system will have specific real-time responsiveness, just as having a powerful engine in a car doesn't by itself guarantee that it will drive like an Indy race car.
Great real-time support in an operating system is necessary, but not sufficient for building a system that provides adequate real-time responsiveness. You also need a CPU that is fast enough to carry the load, device drivers that behave properly, and application software that uses high-priority threads dedicated to doing the time-critical work. And even then, your development team needs to clearly define its real-time goals and measure against these goals early and often.
This article provides a developer's-eye view of the real-time support in Windows CE 3. For readers who are new to real-time, I'll start with a description of key terms related to real-time programming. As you'll see, Windows CE has features in common with desktop systems, but with its own twist. I'll conclude with detailed coverage of the Windows CE 3. Let's start with a look at some terms.
Factors in Real-time System Development When you evaluate an operating system for time-critical support, you start by identifying those features that can affect real-time performance. Figure 1Interrupt Handling Device driver writers call two separate Win32 functions at driver initialization time to glue the pieces together.
This is actually good news, since it means that the Windows CE kernel is quite a bit simpler than the multiprocessor-ready Windows NT and Windows kernel. The downside is that you cannot speed up the execution of a Pocket PC or any other device running Windows CE by dropping another processor in, as you can with some desktop systems.
Another difference from desktop versions of Windows is that Windows CE limits you to 32 simultaneously executing processes no such limit exists on desktop versions of Windows. By the way, this doesn't mean you can create 32 processes yourself. Windows CE itself creates several processes for its own uses. For example, Windows CE takes several bites from the process pie, including one process for the kernel nk.
To find out about other processes that are running, you can use the Remote Process Viewer tool to check for device-specific processes, and plan your process use accordingly. Figure 2 shows several processes in the Remote Process Viewer. Figure 2Processes in the Remote Process Viewer A process in Windows CE is like a typical process found everywhere else in that it represents a unit of ownership.
Threads When I first started looking at Windows CE, I found the presence of threads to be the most surprising and exciting feature. To my knowledge no other platform has begun life with such a powerful capability. Threads are the unit of scheduling on both desktop versions of Windows and Windows CE. Two of the things that a process gets when it starts running are a private address space and a single thread. A process can start additional threads by calling CreateThread and specifying a startup function.
Each thread has its own stack for all the usual things that stacks are used for, including local variables and function call return addresses. There are a few differences between threads on desktop versions of Windows and Windows CE that are worth noting.
For one thing, there are no fibers in Windows CE. Fibers are a lightweight scheduling object supported on both Windows NT and Windows Fibers provide a way to take the allotted time of a single thread and divide it up in a cooperative, nonpreemptive way for different but related activities.
This makes me think that they are worth a second look though obviously not for Windows CE-based development projects. Threads on Windows CE differ from threads on desktop versions of Windows in another important way: Windows CE has a much simpler thread priority model.
On desktop versions of Windows, the process owns a priority class, but then the priority of individual threads gets calculated as a delta of the process priority. In Windows CE, process priority is strictly a thread attribute and is unrelated to the process. Priority]: Message. In order to terminate the whole group of processes, the Kernel process has to be stopped.
The Stop Kernel button lower right corner stops the kernel. By doing so, queued messages that are supposed to be processed are stuck.
A few message windows will pop up to show the contents of the unprocessed parts of the queues of all involved processes. These popup windows are not error messages; they just report what was happening while the Kernel was stopped.
It also provides a tiny test of the timer functionality: A single shot timer can be setup. The due time setting here is absolute, thus the time has to be in the future. Press the Create Timed Event button quickly before the due time expires.
Progress of the timed event approaching its due time is shown next to the button, which has now converted into a Stop Timed Event Button to allow cancellation of the timed event. A message window will popup when the timed event has signaled. It shows the precise time at which the signaled state was detected and how much it deviates from the requested due time.
The output can be stopped for the all output tab Hold Output Button. All output will be queued and the button converts into a Continue Output button until the Continue Output button is pressed. An optional auto cont. The auto cont. The Calibrated Performance Counter Frequency Offset tab shows the offset of the calibrated performance counter frequency. The graph shown in 2. The graphs context menu right mouse button allows saving the graph or clearing the graph's data. Clearing the data will not stop further recording; creation of the graph will continue.
Version 1. Microsecond resolution time stamps are possible on Windows systems. Resolution in the microsecond regime can be observed at accuracies of a few microseconds without distracting the system too much.
Timer functions at the same resolution and accuracy are implemented and tested. Handling many timed events created by those timer functions set up to fire within the same millisecond is tricky but possible. The evaluation at the startup of the services may sometimes take a few seconds and needs all the CPU time. Fine granularity time services are established with the tools described above. System time adjustment following an NTP time server relies on fine granularity of time keeping.
The accuracy obtained when synchronizing to an NTP server is determined by the accuracy of the system time. Granularities of The time keeping has improved with newer windows versions. It is proposed to have very fine granularity.
This is counterproductive when the goal is precise synchronization of the system time to an NTP server. The following second part "Adjustment of System Time" deals with high accuracy system synchronization. Don't miss more details described on the " News " page. A pdf version of the News History can be downloaded here. Windows provides the following simple tools to manage and monitor system time adjustments: The Internet Time GUI and the console application w32tm.
These tools are sufficient to obtain an initial rough estimate of the performance of the Windows internet time synchronization. Synchronization to an internet time server is accomplished directly from the user interface. An internet time provider can be chosen from a list or a new NTP server address can be added to the list.
It is also possible to add an IP address to the list. Adding an IP address may be advisable when the name represents a pool of servers and the server needs to be explicitly indicated.
The common "Update Now" button will attempt to synchronize the system time to the time server. This allows synchronization to take place or it becomes active upon confirmation.
Note: The message " It could also mean that a synchronization process was successfully started. Such processes can last for many hours.
In order to verify the result or progress of the synchronization, another tool has to be run in parallel. The console application w32tm. As a result, the system time and its offset to the time server are dumped to the console every seconds:. Tracking time. Each line consists of the local time , an internal delay time difference between the udp package received and udp package sent on the server side, i. The first output line of w32tm will also resolve the name of the time server time.
This is important because time. However, w32tm resolves the IP of the server currently in use with w32tm. This IP can also be chosen as a server for the synchronization. For example, one of the addresses of the time. The best proof of quality is obtained when the IP address in the internet time GUI described above and the same IP address with the w32tm command are used:.
The results obtained with w32tm are difficult to interpret. When the offset in time is large i. In these cases, the remaining offset is typically larger than a few milliseconds.
However, when the offset is less than a few seconds, an algorithm gently adjusts the offset in small steps.
This procedure can take many hours. It turns out that obtaining detailed insight into this adjustment algorithm by using w32tm is difficult. A more in-depth investigation may uncover the cause of the behavior observed, however, this requires additional software.
Applying the scheme described above frequently gives very dissatisfying results. Sometimes the synchronization results in a time offset that is worse than the offset prior to synchronization. In particular, Windows Vista and Windows 7 show strange behavior, e. A piece of software is necessary to find out the secret of the adjustment algorithm. Actual system time adjustment parameters can be obtained by a call to the function GetSystemTimeAdjustment because Windows performs the system time adjustment through calls to the function SetSystemTimeAdjustment.
A simple program can call GetSystemTimeAdjustment frequently while a system time adjustment is active and evaluate the gains for individual values of lpTimeAdjustment. The function SetSystemTimeAdjustment allows to initiate and control a system time adjustment:.
Intel specifies [ hpetspec. However, an existing HPET will replace this functionality and remove the system time update activity from the RTC periodic interrupt function. Those systems can typically be identified by a specific value of the update period lpTimeIncrement : Therefore they are neither synchronized nor are they in phase by default; additionally they may show specific drifts.
Windows has a clear preference about what hardware resource is to be used for timekeeping. It was already shown in section 2. The evolution of Windows with newly introduced limitations A few relevant combinations are diagnosed and described here.
A call to GetSystemTimeAdjustment reveals a value of for lpTimeIncrement on most platforms running Windows XP or its server variants Some specific hardware may return other values e. Note: A value of represents This is a very common hardware fingerprint. However, according to the gain equation described in 4.
Setting dwTimeAdjustment to any number different from lpTimeIncrement shall result in a system time adjustment. The system time will advance by This way the gains are predictable, a small list shows the obtained gains at the neighborhood of at dwTimeAdjustment from to These numbers are captured on true hardware.
The smallest available adjustment on such a platform is 6. This hardware also consistently follows the gain equation provided by the MSDN description. These Windows versions increment the system time at a fixed period every lpTimeIncrement. This period does not depend on settings of the timer resolution by means of the timeBeginPeriod function.
This is easiest confirmed by polling system file time transitions over a longer period of time with different settings of timeBeginPeriod. As a result, the granularity of the system time is typically in the range of 10 ms to 20 ms. This was a big step towards higher timing accuracy. Windows Vista also introduced the influence of the multimedia timer resolution set by timeBeginPeriod to the update period of the system time: The system time is updated at a period of ActualResolution returned by the function NtQueryTimerResolution.
The following list of system time gains vs. This list discloses some information contained in " It seems that it is not losing time adjustments with values less than 16, but SetSystemTimeAdjustment ignores the lower 4 bits of dwTimeAdjustment. The obtained gain is the same for all dwTimeAdjustment values in one group. The group size is Only the group ranging from to has 17 members. It is yet unclear why the scheme shows this exception. However, the gain equation used for the gain calculation obviously does not apply here.
Therefore, MSDN: "For each lpTimeIncrement period of time that actually passes, lpTimeAdjustment will be added to the time of day" becomes incorrect for this configuration. The periodic interrupt increments the system time and performs the system time adjustment. However, the "lost 4 bits" idea becomes questionable one more time. Groups have either 15 or 16 elements. This portion of software shifts interrupts into groups of interrupts.
A requested interrupt is accompanied by a tolerance to tell the OS by how much it is allowed to shift the interrupt in time. This may affect the update of the system time and has to be diagnosed carefully. Windows 7 does not update the system time by fixed increments. This behavior raises the question of whether a specific gain for a specific value of dwTimeAdjustment remains constant over time.
Careful evaluation of this matter has not confirmed any variation of the gain added advancement of the system time when a constant value of dwTimeAdjustment is applied. Note: This specific asymmetry occurs with the systems interrupt period set the minimum by means of e.
All software packages using SetSystemTimeAdjustment are in serious danger of relying on predictable gains. It should also be noted that there is no dwTimeAdjustment setting for a gain of 0. It was shown in section 4. The scheme observed on Windows VISTA and Windows 7 requires the software to calibrate itself to the appropriate gain for values of dwTimeAdjustment because it cannot be easily evaluated by the given values of lpTimeIncrement and lpTimeAdjustment.
The system time synchronization routines of these newer Windows versions do not seem to take these facts into account. A typical synchronization to an internet time server uses all bits for setting the values of dwTimeAdjustment.
This can be easily monitored through frequent use of GetSystemTimeAdjustment. Furthermore, these tools expect the lower 4 bits to be taken into account by the system. Windows calculates a correction scheme ahead of the actual adjustment based on the offset to the network time. This is accompanied by the fact that there is no monitoring of the internet time provider while the system time adjustment progresses.
Such an adjustment can run for hours and a big deviation may appear with wrong gain estimates resulting from the synchronization algorithm. Finally, at some point the deviation will be several seconds and the next synchronization will only set the local time to the network time without applying the function SetSystemTimeAdjustment. Windows 8 has finally fixed this mishap.
This list has been captured on a Windows 8 system with constant TSC support:. The deviation of gains shown in this list are a result of the changes in Windows 8 timekeeping.
Windows 8 does not increment the system time by constant increments, it rather applies a variety of increments to achieve a desired mean increment. As a consequence, the above measurement would have to be taken over many more periods to show results with less deviations. However, it is very obvious that the described adjustment scheme if fulfilled with Windows 8. As of Windows 8. The same hardware now reports for lpTimeIncrement.
The list of gains appears as follows:. Each value of dwTimeAdjustment produces an individual gain and the result follows the documentation. When operating on a platform with invariant TSC, the scheme looks like this:. This looks very much like the classical Windows XP adjustment gain scheme. The system time adjustment will take care that the system time will progress by TimeAdjustment during TimeIncrement.
This effectively happened with Windows XP. Since Windows 8 on specific hardware also since Windows 7 this process may also appear as a progress in smaller steps, depending on the setting of the timer resolution. When the timer resolution is set to maximum resolution see section 2. However, Windows 8 and Windows 8. Such tolerances are outside the design specification of the W32Time service. MSDN: "If the time difference between the local clock and the selected accurate time sample also called the time skew is too large to correct by adjusting the local clock rate, the time service sets the local clock to the correct time.
A much more detailed view of the system time adjustment can be obtained when the local time is compared to a precise remote time while the system time adjustment is active. The accuracy of w32tm. Also, the accuracy of time. In order to facilitate a closer look at the problems described above, an NTP Network Time Protocol client was added to the time services and the user interface was extended by an NTP Offset tab.
This allows to see how the local time progresses against a reference time. The calibrated performance counter frequency receives an additional correction when a system time adjustment is active. The system time adjustment forces the local time to advance slower or faster, thus the performance counter frequency has to be corrected in a way that takes the modified duration of the "second" during the adjustment into account see section 2.
Consequently, an applied system time adjustment becomes visible in the "Calibrated Performance Counter Frequency Offset" tab. As of version 1. It is referenced to the value given by QueryPerformanceFrequency and scaled to show deviation in parts per million. This way applied system time adjustment gains will directly show in the plot with real numbers. The user interface now also provides two checkboxes.
The "Autoadjust" checkbox enables permanent synchronization of the local time to a network time:. Another status line contains information about the automatic adjustment see section 4. The following two plots were captured when the a system time adjustment was triggered by Windows XP:. The gain was reduced in steps over a long period of time the total adjustment lasted from to around In the first part, the gain was reduced after about the same time until about At that point, the granularity of dwTimeAdjustment prohibited smaller steps and the time between the modifications of dwTimeAdjustment was extended.
This way, the target could be approached with a decreasing adjustment speed. The system time adjustment was still enabled, however the gain was 0. At this point, the system drifted with its own drift rate. In practice, the drift may be higher than the smallest gain setting.
This way, a final adjustment step may not move in the desired direction. This can be seen in Fig. As mentioned, the whole scheme of how and when the various gain settings are applied is worked out ahead of the actual adjustment; however, the local drift can add a considerable offset when the adjustment takes many hours.
As described in 4. The following plot was recorded during an adjustment on Windows The initial offset is about ppm. Due to poor resolution granularity of gain , the sign of the adjustment gain changes after just 2 steps and remains there for a long time at least for another day. This is a typical example of a failing system time adjustment on a Windows 7 system.
The offset time is basically the sum of the adjustments and is completely messed up large negative offset during this attempt. Windows 8 has fixed the limited resolution of dwTimeAdjustment and shows adjustments comparable to Windows XP. The following two plots show a system time adjustment initiated by the Windows 8 internet time GUI:. NTP monitoring was enabled at From this point in time no adjustment was active, the system drifted at about The list shows the progress of the adjustment for each setting of dwTimeAdjustment followed by the period of time during which dwTimeAdjustment was active.
The gain was calculated using the expression given in 4. Consequently, the adjustment contribution and the remaining offset was calculated. The adjustment scheme looks identical to the scheme observed on Windows XP.
Presumably no changes have been made to the systems adjustment tool. However some more details can be extracted from the list above:. The observed offset at the end of the active adjustment was approx. The total adjustment time was s to , 16 x s. The systems drift was At a drift rate of The difference to the observed offset of ms is This corresponds to the remaining offset derived from the adjustment progress table.
This evidently shows that Windows calculates an adjustment scheme based on a one-time offset measurement ahead of the actual adjustment.
Unfortunately the scheme captured here does allow for a remarkable remaining offset. The drift is not taken into account at any time. This way an adjustment, like the adjustment shown here, may take several hours to adjust the offset into the few milliseconds regime and just about the same time to be where the offset was prior to the attempt to adjust.
Larger offsets are not adjusted using such a scheme. An offset of say 10 seconds is simply corrected by setting the system time in one shot. This produces a jump in time which may be confusing to software, particularly when the jump in time is backwards. This can be used to detect changes of system time but it requires a window. However, there is no notification when the system time is adjusted. As a result, the system time changes gradually without any notification other than the actual changes in the flow of time.
The only way to check this is through a frequent call to GetSystemTimeAdjustment. This is an obvious drawback. The state of such asynchronous behavior can only be closely estimated by calling GetSystemTimeAdjustment frequently. Time control with high accuracy, as proposed by the Windows Timestamp Project, cannot accept the uncertainties and inaccuracies described here. The proposed solution is continuous synchronization of the system time to a network time using NTP. Synchronizations of the local time may still occur asynchronously when scheduled by the operating system; however, the service described here is capable of detecting and canceling them.
Nevertheless, disabling the automatic synchronization provided by Windows see the Windows GUI in section 1 is recommended in order to obtain the greatest accuracy.
NTP monitoring was started at around and the local time drifted at a rate of about The NTP offset increased from around 0. At about , the autoadjust was enabled and the local time was synchronized to the network time. The effect of the system time adjustment on the performance counter frequency has been described in section 4.
0コメント