On 4/27/07, Phrogz [email protected] wrote:
[snip]
I think Time.now.usec on windows is just whack. 
Here’s a quick c extension for windows that can do super accurate
waiting:
///////////////////////////////////
#include “ruby.h”
#include “windows.h”
VALUE rb_cHotwait;
__int64 Hotwait_freq;
VALUE Hotwait_wait( VALUE inSelf, VALUE inWaitTime )
{
__int64 theStartTime;
__int64 theCounter;
__int64 theDifference=0;
double theWaitTime = NUM2DBL(inWaitTime);
theWaitTime *= Hotwait_freq;
QueryPerformanceCounter( &theStartTime );
while( theDifference < theWaitTime )
{
QueryPerformanceCounter( &theCounter );
theDifference = theCounter - theStartTime;
Sleep(0);
}
return rb_float_new( (float)theDifference / (float)Hotwait_freq );
}
void Init_hotwait()
{
QueryPerformanceFrequency( &Hotwait_freq );
rb_cHotwait = rb_define_class( “Hotwait”, rb_cObject );
rb_define_singleton_method( rb_cHotwait, “wait”, Hotwait_wait, 1 );
}
///////////////////////////////////
Used like this:
############
require ‘hotwait’
10.times {
puts “Time.now.usec : #{Time.now.usec/1000}”
puts “QueryPerfCounter: #{”%.4f"%Hotwait.wait( 0.01 )}"
}
############
It produces this:
Time.now.usec : 718
QueryPerfCounter: 0.0100
Time.now.usec : 718
QueryPerfCounter: 0.0100
Time.now.usec : 734
QueryPerfCounter: 0.0100
Time.now.usec : 750
QueryPerfCounter: 0.0100
Time.now.usec : 750
QueryPerfCounter: 0.0100
Time.now.usec : 765
QueryPerfCounter: 0.0100
Time.now.usec : 781
QueryPerfCounter: 0.0100
Time.now.usec : 796
QueryPerfCounter: 0.0100
Time.now.usec : 796
QueryPerfCounter: 0.0100
Time.now.usec : 812
QueryPerfCounter: 0.0100
And now it’s past my bedtime. (:
-Harold