Skip to content

Instantly share code, notes, and snippets.

@pfitzseb
Created December 5, 2018 20:49
Show Gist options
  • Save pfitzseb/5566b0e53de6f794837b1def2e815e21 to your computer and use it in GitHub Desktop.
Save pfitzseb/5566b0e53de6f794837b1def2e815e21 to your computer and use it in GitHub Desktop.
sleep ns julialang
# 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
@pfitzseb
Copy link
Author

pfitzseb commented Dec 5, 2018

julia> @btime sleep_ns(1e-6)
  1.080 μs (0 allocations: 0 bytes)
8.0e-8

julia> @btime sleep_ns(1e-7)
  269.978 ns (0 allocations: 0 bytes)
1.7e-7

julia> @btime sleep_ns(5e-7)
  539.958 ns (0 allocations: 0 bytes)
4.0e-8

julia> @btime sleep_ns(1e-6)
  1.080 μs (0 allocations: 0 bytes)
8.0e-8

julia> @btime sleep_ns(8e-6)
  8.099 μs (0 allocations: 0 bytes)
9.9e-8

julia> @btime sleep_ns(1e-9)
  269.978 ns (0 allocations: 0 bytes)
2.69e-7

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment