IOS Precision Timers

Source: Internet
Author: User

Do I need a high precision timer?

Don ' t use a high precision timer unless you really need it. They consume compute cycles and battery. There can only is a limited number of high precsion timers active at once. A High Precision Timer is ' first in line ', and not every timer can be first. When too many try, all the timers lose accuracy.

Example applications that is candidates for high precision timers is games this need to provide precise frame rates, or Daemons that is streaming data to hardware with limited buffering, such as audio or video data.

Back to Top

A suggestion for synchronizing with display updates

If you ' re writing code that needs to synchronize with frame buffer or display updates, Apple have already done much of the Hard work for you. If you is developing for IOS, please see the Cadisplaylink class, found in the quartzcore.framework. If you is targeting OS X, see Cvdisplaylink, also found in Quartzcore.framework.

Ios:cadisplaylink Class Reference

OS X:cvdisplaylink Reference

Back to Top

How does timers work?

There is many API ' s in IOS and OS X is waiting for a specified period of time. They may is Objective C or C, and they take different kinds of arguments, but they all end up using the same code inside T He kernel. Each timer API tells the kernel it needs-to-wait until a certain time, for example seconds from now. The kernel keeps track of every thread, and if a timer request comes in, that thread was marked as "I ' d like to run in 10 Seconds ".

The kernel tries to being as frugal as possible with CPU cycles, so if there are no other work-to-do, it would put the CPU ' s to Sleep for ten seconds, then wake up and run your thread.

Of course, that's an optimum situation, and in the real world, things never seem to work that easily! In a real situation, there is many threads that want to run, and many threads making timer requests, and the kernel have t O Manage them all. With thousands of threads and only a few CPU ' s, it easy-to-see how timers might is inaccurate.

Back to Top

How does high precision timers work?

The only difference between a regular timer and a high precision timer is the scheduling class of the thread making the TI Mer request. Threads that is in the real time scheduling class get first class treatment. They go to the front of the line whenever they need to run. If There is a conflict with multiple threads wanting to run in ten seconds, a real time thread always goes first.

Back to Top

How does I get put into the real time scheduling class?

Listing 1 The following code would move a pthread to the real time scheduling class

#include <mach/mach.h>
#include <mach/mach_time.h>
#include <pthread.h>
void Move_pthread_to_realtime_scheduling_class (pthread_t pthread)
{
    mach_timebase_info_data_t Timebase_info;
    Mach_timebase_info (&timebase_info);
    Const uint64_t nanos_per_msec = 1000000ULL;
    Double clock2abs = (double) timebase_info.denom/(double) timebase_info.numer) * NANOS_PER_MSEC;
    thread_time_constraint_policy_data_t policy;
    Policy.period      = 0;
    Policy.computation = (uint32_t) (5 * clock2abs); 5 ms of work
    Policy.constraint  = (uint32_t) (ten * clock2abs);
    policy.preemptible = FALSE;
    int kr = Thread_policy_set (PTHREAD_MACH_THREAD_NP (Pthread_self ()),
                   Thread_time_constraint_policy,
                   (thread_policy_t) &policy,
                   Thread_time_constraint_policy_count);
    if (kr! = kern_success) {
        Mach_error ("Thread_policy_set:", KR);
        Exit (1);
    }
}

The period, computation, constraint, and preemptible fields does have a effect, and more can is learned about them at:

Using the Mach Thread API to influence scheduling

Back to Top

Which timing API (s) should I use?

As mentioned above, all the timer methods end-in-the-same place inside the kernel. However, some of them is more efficient than the others. At the time of this note were written, Mach_wait_until () is the API we would recommend using. It has the lowest overhead of all the timing APIs that we measured. However, if you had specific needs that aren ' t met by Mach_wait_until (), for example you need to wait on a condvar, then Feel the appropriate timer API.

Listing 2 This example code demonstrates using Mach_wait_until () to wait exactly seconds.

#include <mach/mach.h>
#include <mach/mach_time.h>
static const uint64_t NANOS_PER_USEC = 1000ULL;
static const uint64_t NANOS_PER_MILLISEC = 1000ULL * NANOS_PER_USEC;
static const uint64_t NANOS_PER_SEC = 1000ULL * NANOS_PER_MILLISEC;
Static mach_timebase_info_data_t Timebase_info;
Static uint64_t Abs_to_nanos (uint64_t ABS) {
    Return ABS * Timebase_info.numer  /timebase_info.denom;
}
Static uint64_t Nanos_to_abs (uint64_t Nanos) {
    return Nanos * Timebase_info.denom/timebase_info.numer;
}
void Example_mach_wait_until (int argc, const char * argv[])
{
    Mach_timebase_info (&timebase_info);
    uint64_t time_to_wait = nanos_to_abs (10ULL * nanos_per_sec);
    uint64_t now = Mach_absolute_time ();
    Mach_wait_until (now + time_to_wait);
}
Back to Top

How accurate should-precision timers be?

Timer accuracy depends on many factors, including the type of hardware being run on, the load in that hardware, and the PO Wer available (battery vs plugged in). However, if an otherwise unloaded machine or device was consistently missing your scheduled time by + than NDS, that should is considered an error, please file a bug with Apple. Often times we can do much better than this, but it best to measure for yourself.

Timers is not accurate across a sleep and wake cycle of the hardware.

Back to Top

What is the do ' and dont's of code running with high precision timers?

Do use as little CPU as possible during your timer loop. Remember that your the thread now have special privileges, and when you ' re running, no one else can. Do try to stretch out your timer requests as much as you safely can. This allows the kernel to use less battery by sleeping more often and longer.

Don ' t spin loop! This burns CPU and battery at very high rates, and when newer faster hardware are released you ' ll burn CPU and battery even faster!

Don ' t create large numbers of real time threads. Real time scheduling isn ' t magic, it works by making your thread higher priority than other threads on the system. If everyone tries to crowd to the front of the line, all the real time threads would fail

Windows platform GetTickCount functions like this, find a function called Mach_absolute_time (), but Apple's documentation is very

Give force, find a half genius more clear is how, originally this function returns the value is only after start system Cpu/bus clock A tick number, differs from GetTickCount,

Because this GetTickCount is the number of milliseconds after the system starts, it takes a conversion to get the time after the system starts

Https://developer.apple.com/library/ios/technotes/tn2169/_index.html

IOS Precision Timers

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.