我现在在需要高精度定时(微秒级别),可是发现定时器运行的时候,定时精度达不到我的要求,即使是timer_creat()产生的定时器,依旧出现较大的误差。我改如何解决问题的。
如下是我参考QNX下的例程,稍作修改,希望可以在每10us打印一句话,可是发现,我使用时间戳来计时和定时器的10us差距挺大。
/*
/*
* Demonstrate how to set up a timer that, on expiry,
* sends us a pulse. This example sets the first
* expiry to 10 us and the repetition interval
* to 10 us.
*/
#include <stdio.h>
#include <time.h>
#include <sys/netmgr.h>
#include <sys/neutrino.h>
#include <errno.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <time.h>
#include <stdlib.h>
#define MY_PULSE_CODE _PULSE_CODE_MINAVAIL
#define NSEC_PER_SEC 1000000000
typedef union
{
struct _pulse pulse;
/* your other message structures would go here too */
} my_message_t;
main()
{
struct sigevent event;
struct itimerspec itime;
struct timespec stop,start,res;
struct _clockperiod *new;
timer_t timer_id;
int chid;
int rcvid;
my_message_t msg;
chid = ChannelCreate(0);
event.sigev_notify = SIGEV_PULSE;
event.sigev_coid = ConnectAttach(ND_LOCAL_NODE, 0,
chid,
_NTO_SIDE_CHANNEL, 0);
event.sigev_priority = getprio(0);
event.sigev_code = MY_PULSE_CODE;
new = (struct _clockperiod *)malloc(sizeof(struct _clockperiod));
new->nsec = 1000L;
new->fract = 0L;
ClockPeriod(CLOCK_REALTIME,new,NULL,0);
free(new);
if ( clock_getres( CLOCK_REALTIME, &res) == -1 )
{
perror( "clock get resolution" );
return EXIT_FAILURE;
}
printf("The resolution is %ld ns.\n\n\n",res.tv_nsec);
timer_create(CLOCK_REALTIME, &event, &timer_id);
itime.it_value.tv_sec = 0;
/* 10,000 nsecs = 10us */
itime.it_value.tv_nsec = 10000;
itime.it_interval.tv_sec = 0;
/* 10,000 nsecs = 10 us */
itime.it_interval.tv_nsec = 10000;
timer_settime(timer_id, 0, &itime, NULL);
/*
* As of the timer_settime(), we will receive our pulse
* in 10 microseconds (the itime.it_value) and every 10
* microseconds thereafter (the itime.it_interval)
*/
for (;;)
{
rcvid = MsgReceive(chid, &msg, sizeof(msg), NULL);
if (rcvid == 0)
{ /* we got a pulse */
if (msg.pulse.code == MY_PULSE_CODE)
{
clock_gettime( CLOCK_REALTIME, &stop) == -1;
printf("we got a pulse from our timer\n");
printf("The sample time %ld ns.\n",(stop.tv_sec - start.tv_sec)*NSEC_PER_SEC + stop.tv_nsec-start.tv_nsec);
start = stop;
} /* else other pulses ... */
} /* else other messages ... */
}
}
运行的部分结果
we got a pulse from our timer
The sample time 999847 ns.
we got a pulse from our timer
The sample time 999847 ns.
we got a pulse from our timer
The sample time 999847 ns.
we got a pulse from our timer
The sample time 999847 ns.
we got a pulse from our timer
The sample time 999847 ns.
we got a pulse from our timer
The sample time 999847 ns.
we got a pulse from our timer
The sample time 999847 ns.
we got a pulse from our timer
The sample time 999847 ns.
we got a pulse from our timer
The sample time 999847 ns.
we got a pulse from our timer
The sample time 999847 ns.
we got a pulse from our timer
The sample time 999847 ns.
we got a pulse from our time