Macos OSX上的常规计时器回调
我试图在OSX上每隔N毫秒(理想情况下是1毫秒)获得一次回调。我设置了一个Macos OSX上的常规计时器回调,macos,timer,scheduling,Macos,Timer,Scheduling,我试图在OSX上每隔N毫秒(理想情况下是1毫秒)获得一次回调。我设置了一个CFRunLoop,然后添加了一个计时器,如下所示: const double period = 0.001; CFAbsoluteTime now = CFAbsoluteTimeGetCurrent(); CFRunLoopTimerContext context; std::memset(&context, 0, sizeof(context)); context.info = ...; CFRunLo
CFRunLoop
,然后添加了一个计时器,如下所示:
const double period = 0.001;
CFAbsoluteTime now = CFAbsoluteTimeGetCurrent();
CFRunLoopTimerContext context;
std::memset(&context, 0, sizeof(context));
context.info = ...;
CFRunLoopTimerRef timerRef = CFRunLoopTimerCreate(kCFAllocatorDefault, now + period, period, 0, 0, RunLoopTimerCallBack, &context);
// Add it to the loop.
CFRunLoopAddTimer(/* my run loop reference */, timerRef, kCFRunLoopDefaultMode);
它似乎可以工作-myRunLoopTimerCallback()
大约每毫秒调用一次。除非它没有。报告说:
如果存在实现原因,可以通过计时器稍微调整间隔的精细精度(最多亚毫秒)
因此,我希望它或多或少能起作用,但实际上,我在两次回调之间会出现长达8毫秒的延迟:
我试过了,但没什么不同。有人知道我为什么会被耽搁吗?我意识到这对操作系统是一个很大的推动,也许这是一个计划的问题,但仍然。。。1毫秒没那么短。事实上,我是个白痴。设置实时线程优先级会产生巨大的差异。结果如下: 下面是我使用的代码:
#include <mach/mach_time.h>
#include <mach/thread_policy.h>
#include <iostream>
using namespace std;
void SetPriorityRealtime()
{
mach_timebase_info_data_t timebase;
kern_return_t kr = mach_timebase_info(&timebase);
if (kr != KERN_SUCCESS)
{
cerr << "Warning: Couldn't get timebase." << endl;
return;
}
// The number of nanoseconds per tick is:
cerr << timebase.numer << " / " << timebase.denom << endl;
// Set the thread priority.
thread_time_constraint_policy ttcpolicy;
thread_port_t threadport = pthread_mach_thread_np(pthread_self());
// In ticks. Therefore to convert nanoseconds to ticks multiply by (timebase.denom / timebase.numer).
ttcpolicy.period = 500 * 1000 * timebase.denom / timebase.numer; // Period over which we demand scheduling.
ttcpolicy.computation = 100 * 1000 * timebase.denom / timebase.numer; // Minimum time in a period where we must be running.
ttcpolicy.constraint = 100 * 1000 * timebase.denom / timebase.numer; // Maximum time between start and end of our computation in the period.
ttcpolicy.preemptible = FALSE;
kr = thread_policy_set(threadport, THREAD_TIME_CONSTRAINT_POLICY, (thread_policy_t)&ttcpolicy, THREAD_TIME_CONSTRAINT_POLICY_COUNT);
if (kr != KERN_SUCCESS)
{
cerr << "Warning: Couldn't set thread policy: " << kr << endl;
return;
}
}
#包括
#包括
#包括
使用名称空间std;
void SetPriorityRealtime()
{
马赫时基信息数据时基;
kern\u return\u t kr=mach\u timebase\u info(&timebase);
if(kr!=KERN_SUCCESS)
{
cerr你在哪里生成这些图形的?我很确定我只是记录了回调时间,并在Excel中绘制了连续图形之间的差异。对于其他阅读本文的人来说:这也适用于iOS。