您的位置:首页 > 其它

DOS下面关于精确延时1ms的函数(理论上可以非常精确延时到10微妙级别)

2009-01-13 15:02 741 查看
在微软的MSC7.0以及MSVC1.52下面都没有Borland C++的精确延时函数:delay(经过测试可以非常精确的延时到1ms)
同时看了一下计时器的相关内容,自己写了一个精确延时函数,但不敢保证在所有的电脑上都可以精确延时
源代码:
/***
*void xdelay(unsigned int ms)
*
*Purpose:
* Make an exactly millisecond delay
*
*Entry:
* unsigned int ms - The delay time (millisecond)
*
*Exit:
* void
*
*Exceptions:
* Note:
* .This function was created by Denny at Jun/26/2008
* .Dongguan Siliten Electronics CO., LTD.
* .The timer frequency is 1193180Hz
* .The timer counter is 16bits, so only elapsed 55ms for/
* counter a circle.
*
*******************************************************************************/
void xdelay(unsigned int ms)
{
unsigned int base_counter;
unsigned int circle;
unsigned int counter;
unsigned int last_counter;
unsigned long end;
unsigned long cur;

disable();
//outportb(0x43, 0x30);
base_counter = inportb(0x40);
base_counter += inportb(0x40)<<8;
enable();
circle = 0;
last_counter = 0;
end = (unsigned long)ms*1193;
cur = 0;
while (end > cur)
{
disable();
counter = inportb(0x40);
counter += inportb(0x40)<<8;
enable();
counter = base_counter - counter;
if (counter-last_counter > 50) // Illegal data
{
last_counter = counter;
continue;
}
if ( (counter < last_counter) && (last_counter > 65000) && (counter < (65536-65000)) )
circle++;
cur = ((unsigned long)circle<<16) + counter;
//printf("base:%u|cir:%u|cnt:%u|last:%u|end:%lu|cur:%lu/n", base_counter, circle, counter, last_counter, end, cur);
last_counter = counter;
}
}

下面是测试程序:
ClrScr();
for (i = 0; i < 5; i++)
{
printf("delay(1000):%d/r/n", i);
for (j = 0; j < 1; j++)
delay(1000);
}
for (i = 0; i < 5; i++)
{
printf("delay(100):%d/r/n", i);
for (j = 0; j < 10; j++)
delay(100);
}
for (i = 0; i < 5; i++)
{
printf("delay(10):%d/r/n", i);
for (j = 0; j < 100; j++)
delay(10);
}
for (i = 0; i < 5; i++)
{
printf("delay(1):%d/r/n", i);
for (j = 0; j < 1000; j++)
delay(1);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐