From: Harold Hausman Date: 2007-04-28T00:57:26+09:00 Subject: Re: 10 millisecond delay/callback On 4/27/07, Phrogz wrote: > On Apr 26, 2:06 pm, khai...@enigo.com wrote: > > On Fri, 27 Apr 2007, Earle Clubb wrote: > > > I need to perform a task every 10ms. I've been using > > > kernel.sleep(0.01), but sleep seems to be slow and erratic at sub-second > > > resolutions. Here's a test I ran along with the results: > [snip] > > Try select() > [snip] > > No such glory on Windows: > > [snip] I think Time.now.usec on windows is just whack. :P 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