我正在开发一个用C编写的游戏服务器.我需要开发一个具有一定频率的周期(每秒50次)
执行算法.
问题是我无法暂停程序的精确时间间隔 – 20000微秒.
功能usleep(20000)运行约30000微秒.
结果总是超过预期的10000微秒.
执行算法.
问题是我无法暂停程序的精确时间间隔 – 20000微秒.
功能usleep(20000)运行约30000微秒.
结果总是超过预期的10000微秒.
这是我的简单代码示例:
#include <stdio.h> #include <time.h> #include <unistd.h> int main( int argc,char ** argv ) { const unsigned long long nano = 1000000000; unsigned long long t1,t2; struct timespec tm; for(;;) { clock_gettime( CLOCK_REALTIME,&tm ); t1 = tm.tv_nsec + tm.tv_sec * nano; usleep( 20000 ); clock_gettime( CLOCK_REALTIME,&tm ); t2 = tm.tv_nsec + tm.tv_sec * nano; printf( "delay: %ld\n",( t2 - t1 ) / 1000 ); } return 0; }
它的运行结果:
$./a.out delay: 29233 delay: 29575 delay: 29621 delay: 29694 delay: 29688 delay: 29732 delay: 29709 delay: 29706 delay: 29666 delay: 29702 delay: 29702 delay: 29705 delay: 29789 delay: 29619 delay: 29785 delay: 29634 delay: 29692 delay: 29708 delay: 29701 delay: 29703
我也尝试使用函数select(),但结果与sleep()相同.
请告诉我,我的代码怎么了?
P.S:
$uname -a FreeBSD home.com 9.0-RELEASE FreeBSD 9.0-RELEASE #0: Tue Jan 3 07:46:30 UTC 2012 root@farrell.cse.buffalo.edu:/usr/obj/usr/src/sys/GENERIC amd64