[fpc-pascal] Microsecond Delay Suggestions?

Sven Barth pascaldragon at googlemail.com
Tue Jul 26 20:06:21 CEST 2016


On 26.07.2016 19:05, Dmitry Boyarintsev wrote:
> On Tue, Jul 26, 2016 at 12:38 PM, James Richters
> <james at productionautomation.net <mailto:james at productionautomation.net>>
> wrote:
> 
>     What I need is a timer that I can specify in microseconds, a
>     millisecond is too long.   I am using it for timing to read in a
>     string on a serial connection.  My fastest baudrate is 250000, so at
>     that rate I would need to delay only 36 microseconds.  So I can’t
>     use sleep () or delay () because they only go down to 1mS and that’s
>     too slow.
> 
> 
> Here's an example of Sleep with microseconds that I came up with
> 
> procedure SleepMcs(mcs: Int64);
> var
>   ct : TLargeInteger;
>   fr : TLargeInteger;
>   af  : TLargeInteger;
>   trg : TLargeInteger;
> const
>   NanoInMicro = 1000;
> begin
>   QueryPerformanceCounter(ct);
>   QueryPerformanceFrequency(fr);
>   trg:=round(mcs * NanoInMicro / (NSInSec/fr));
>   repeat
>     QueryPerformanceCounter(af);
>   until trg<=(af-ct);
> end;
> 
> I'm hoping that there's a better solution out there, because this
> procedure will end up with 100% CPU load.
> I doubt it's possible to unload the CPU, since the windows scheduler is
> in milliseconds accuracy.
> May be a lower (kernel/driver) level allows that.

An alternative would be NtDelayExecution from unit jwanative. Its
interval argument is in multiples of 100ns and is essentially what
Windows' Sleep() uses internally.
Note: The first argument "Alertable" determines whether the function can
be interrupted by NtAlertThread (and whatever Windows API functions use
that internally).

Regards,
Sven




More information about the fpc-pascal mailing list