# Accuracy of sleep()

**URL:** https://discourse.julialang.org/t/accuracy-of-sleep/5546
**Category:** General Usage
**Tags:** question
**Created:** [August 24, 2017, 8:02pm UTC](https://discourse.julialang.org/t/accuracy-of-sleep/5546 "2017-08-24T20:02:23Z")
**Posts on this page:** 5
**Page:** 1

<div class="post-metadata">

### Author: ![baggepinnen](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/baggepinnen/32/693_2.png) [@baggepinnen](https://discourse.julialang.org/u/baggepinnen)
#### Post date: [August 24, 2017, 8:02pm UTC](https://discourse.julialang.org/t/accuracy-of-sleep/5546/1 "2017-08-24T20:02:23Z")

</div>

# Problem

I didn’t expect `sleep(seconds)` to be super accurate, but I must admit I was surprised over how inaccurate it is. See a benchmark below. Relative error of 10% for sleep times under 0.01 seconds is quite a lot, and may cause potential issues in, e.g., real-time control loops.

```julia
using Plots
function testsleep()
    sleeptimes = logspace(-3,1,50)
    actual_sleeptimes = map(sleeptimes) do st
        @elapsed sleep(st)
    end
    sleeptimes, actual_sleeptimes
end
sleeptimes, actual_sleeptimes = testsleep()
diff = actual_sleeptimes-sleeptimes
plot(sleeptimes, [diff diff./sleeptimes], xlabel="Sleeptimes", ylabel=["Absolute difference" "Relative difference"],
    xscale=:log10, yscale=[:linear :log10], ylims=[(0,1e-2) :auto], layout=2, legend=false)

```

 ![sleep](https://global.discourse-cdn.com/julialang/original/3X/a/c/ac0f1a3e6f2cf06db7ead75f4a4af48b1b67b843.png)

# Compensation

One can potentially model the time difference and compensate for it. For sleeptimes close to the lower limit of `1e-3`s, preliminary testing indicates that one can reduce the relative error about one order of magnitude with a simple polynomial model:

```julia
A = log.(sleeptimes).^(0:2)' # Regressor matrix
x = A\log.(actual_sleeptimes) # Polynomial coeffs
e = log.(actual_sleeptimes) - A*x

predicted_time(t) = exp((log(t).^(0:2)')*x)
predicted_difference(t) = predicted_time(t)-t

plot(sleeptimes, [actual_sleeptimes predicted_time.(sleeptimes)], lab=["Actual", "Predicted"], xlabel="Sleeptime", yscale=:log10, xscale=:log10)
plot(sleeptimes, [abs.(diff-predicted_difference.(sleeptimes)) abs.(diff-predicted_difference.(sleeptimes))./sleeptimes],
        xlabel="Sleeptimes", ylabel=["Absolute prediction error" "Relative prediction error"],
        xscale=:log10, yscale=[:linear :log10], ylims=[(0,1e-2) :auto],
        layout=2, legend=false)

# Estimated parameters stat. significant?
σ² = var(e) # Prediction error variance
Σ = σ²*inv(A'A) # Parameter covariance
p05 = abs.(x)./sqrt.(diag(Σ)) .> 1.96 # Significant?

5-element BitArray{1}:
 false
  true
 false
 false
  true

```

 ![compensated](https://global.discourse-cdn.com/julialang/original/3X/1/3/136e95c4337bd862af6b4dd2ac01d6ea870f0bf3.png)

# Question

Does anyone have experience with this before and have suggestions on a more accurate strategy. I’ll see how reproducible the results are on a different system tomorrow and try to improve upon my quick and dirty high-order polynomial model.

---

<div class="post-metadata">

### Author: ![kristoffer.carlsson](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/kristoffer.carlsson/32/22_2.png) [@kristoffer.carlsson](https://discourse.julialang.org/u/kristoffer.carlsson)
#### Post date: [August 24, 2017, 8:35pm UTC](https://discourse.julialang.org/t/accuracy-of-sleep/5546/2 "2017-08-24T20:35:30Z")

</div>

[https://github.com/JuliaLang/julia/issues/12770](https://github.com/JuliaLang/julia/issues/12770)

---

<div class="post-metadata">

### Author: ![baggepinnen](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/baggepinnen/32/693_2.png) [@baggepinnen](https://discourse.julialang.org/u/baggepinnen)
#### Post date: [August 24, 2017, 8:55pm UTC](https://discourse.julialang.org/t/accuracy-of-sleep/5546/3 "2017-08-24T20:55:20Z")

</div>

Thanks for the link!  
`usleep(usecs) = ccall(:usleep, Cint, (Cuint,), usecs)`  
seems way more accurate.

---

<div class="post-metadata">

### Author: ![TsurHerman](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tsurherman/32/1234_2.png) [@TsurHerman](https://discourse.julialang.org/u/TsurHerman)
#### Post date: [August 24, 2017, 9:07pm UTC](https://discourse.julialang.org/t/accuracy-of-sleep/5546/4 "2017-08-24T21:07:54Z")

</div>

Sleep also frees the main thread to do other asynchronous stuff, while I think calling usleep using ccall might be “blocking” so there is that to consider too.

---

<div class="post-metadata">

### Author: ![John\_Hearns](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/john_hearns/32/1685_2.png) [@John\_Hearns](https://discourse.julialang.org/u/John_Hearns)
#### Post date: [August 26, 2017, 6:56am UTC](https://discourse.julialang.org/t/accuracy-of-sleep/5546/5 "2017-08-26T06:56:28Z")

</div>

I found this very good article about how Linux keeps time

> **[Measuring Latency in Linux - Confessions of a Wall Street Programmer](http://btorpey.github.io/blog/2014/02/18/clock-sources-in-linux/)**
>
> How to accurately measure latency on Linux

By a Wall Street programmer, so she/he should know about latency!  
I guess the HPET stuff is a bit specific to the Intel architecture though. Anyone care to comment about other architectures?
