Subject: Re: microtime(9) slow on i386?
To: None <tech-perform@netbsd.org>
From: sudog <sudog@sudog.com>
List: tech-perform
Date: 10/22/2001 14:48:39
On Monday 22 October 2001 14:14, Wolfgang Rupprecht wrote:
> jdolecek@netbsd.org (Jaromir Dolecek) writes:
> > Upon further investigation, it shows that microtime(9) on i386 uses
> > port i/o, which is very slow on modern processors. Is there a way
> > to improve this? This could help system overall, since microtime(9)
> > is used quite often.
>
> I was using this to profile some userland code, but a similar hack
> should work in the kernel.  The most pressing gotcha is that units
> output are processor clock ticks not seconds, so one needs to scale it
> somewhere.
>
> inline          u64
> getTick64(void)
> {
>     u64             ticks;
>     asm             volatile("rdtsc":"=A"(ticks));
>     return ticks;
> }
>
> The nice thing about this is that it is very fast.  The count comes
> from a 64-bit internal CPU register, so no external data fetch is
> needed.

This is kind of neat--I'm currently using times() to retrieve clock ticks 
for an event queue I'm writing, since times() was a convenient way of 
grabbing a single time-like value that was always increasing, without 
doing all kinds of math to convert any of the various time structures into 
a long long or quad. Turns out getrusage and friends are the real guts of 
the (now obsolete) times() call, so something like this little asm routine 
would be very nice.

Is there a "right" way of grabbing a clean, portable sub-second timer that 
is guaranteed to always be increasing whether the system admin touches the 
clock or not?

I suppose I could just store the events based on how much time I have to 
wait until they need to be dealt with, but then insertion into the queue 
starts to get hard as does various book-keeping duties.

marc