Article View: comp.os.msdos.programmer
Article #2227Re: How can I get a timed delay of 1 millisecond ?
From: D'Arcy J.M. Cain
Date: Fri, 14 Sep 1990 15:19
Date: Fri, 14 Sep 1990 15:19
44 lines
2525 bytes
2525 bytes
In article <6250@castle.ed.ac.uk> elee24@castle.ed.ac.uk (H Bruce) writes:
>What is the best way to get a program to wait for one milliosecond ?
>(I am using Microsoft C V5.1).
>
Unfortunately the best granularity is about 10/182 of a second since the
system clock ticks at about 18.2 times per second. It's even worse because
you could be of by almost 10/182 of a second because you don't know if you
are sampling at the start or the end of a tick. If you know what the speed
of your CPU is you can perform instructions that take the required amount of
time to complete. There are two disadvantages to this. You have to resort
to assembler which may be a problem for some, and more importantly, events
asynchronous to your program (interupts) may distort the timing.
If you can live with about 1/10 sec granularity here is a simple timing
construct. First set up a pointer to a far time_t (long if your compiler
doesn't understand time_t) and initialize it to location 0x046c. This is
a memory location which is updated at every clock tick. Then read the value
at that location and add the wait value and keep checking the location. Here
is a simple function to do this.
void pause(int tenths)
{
time_t far *cur_time = (time_t far *)(0x046c);
time_t end_time = *cur_time;
/* note that we get the current time as soon as possible in the fewest */
/* number of instructions in order to get the most accurate start time */
/* now we will add the number of ticks to get the real end time */
end_time += (tenths * 182)/100; /* each tenths is 1.82 ticks */
while (end_time > *cur_time) /* wait till time is up.
;
}
You can get fancier if you want but this is the basic idea. Note that
this routine will fail at midnight when the clock rolls over but that's
a really small window. If it is really important you can modify the code
to account for this.
--
D'Arcy J.M. Cain (darcy@druid) |
D'Arcy Cain Consulting | MS-DOS: The Andrew Dice Clay
West Hill, Ontario, Canada | of operating systems.
+ 416 281 6094 |
Technical Details
Message-ID:
<1990Sep14.151951.18485@druid.uucp>Path:
arc1-ca.pugleaf.net!utzoo!utgpu!news-server.csri.toronto.edu!torsqnt!lethe!druid!darcyReferences:
<6250@castle.ed.ac.uk>Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!utzoo!utgpu!news-server.csri.toronto.edu!torsqnt!lethe!druid!darcy From: darcy@druid.uucp (D'Arcy J.M. Cain) Newsgroups: comp.os.msdos.programmer Subject: Re: How can I get a timed delay of 1 millisecond ? Message-ID: <1990Sep14.151951.18485@druid.uucp> Date: 14 Sep 90 15:19:51 GMT References: <6250@castle.ed.ac.uk> Organization: D'Arcy Cain Consulting, West Hill, Ontario Lines: 44