Created
          December 5, 2018 20:49 
        
      - 
      
- 
        Save pfitzseb/5566b0e53de6f794837b1def2e815e21 to your computer and use it in GitHub Desktop. 
    sleep ns julialang
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | # adapted from https://github.com/ArchieCall/AccurateSleep/blob/master/src/hybrid_sleep.jl | |
| function sleep_ns(sleep_time::Float64, threshold::Float64 = 0.001) | |
| tics_per_sec = 1_000_000_000.0 | |
| nano1 = time_ns() | |
| nano2 = nano1 + (sleep_time * tics_per_sec) | |
| min_true_sleep = 0.001 | |
| # normal sleep | |
| if sleep_time > threshold | |
| actual_sleep_time = max(min_true_sleep, sleep_time - threshold) | |
| sleep(actual_sleep_time) | |
| end | |
| # final busy wait | |
| nano3 = time_ns() | |
| while true | |
| nano3 >= nano2 && break | |
| nano3 = time_ns() | |
| end | |
| seconds_over = (nano3 - nano2) / tics_per_sec # overshot | |
| return seconds_over | |
| end | 
      
      
  Author
  
  
        
      
            pfitzseb
  
      
      
      commented 
        Dec 5, 2018 
      
    
  
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment