-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
a6f45ef
commit edb2846
Showing
1 changed file
with
16 additions
and
14 deletions.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,39 +1,41 @@ | ||
-module(funbox_utimer). | ||
|
||
%% API | ||
-export([sleep/1]). | ||
-export([seconds/1]). | ||
-export([sleep/1]). | ||
|
||
%%%=================================================================== | ||
%%% API | ||
%%%=================================================================== | ||
|
||
-spec sleep(non_neg_integer()) -> ok. | ||
sleep(Time) when is_integer(Time), Time >= 2000 -> | ||
{ElapsedTime, _} = timer:tc(timer, sleep, [Time div 1000 - 1]), | ||
sleep(Time - ElapsedTime, monotonic_time()); | ||
sleep(Time) when is_integer(Time), Time >= 0 -> | ||
sleep(Time, monotonic_time()). | ||
|
||
-spec seconds(Seconds) -> MicroSeconds when | ||
Seconds :: non_neg_integer(), | ||
MicroSeconds :: non_neg_integer(). | ||
seconds(Seconds) -> | ||
1000 * 1000 * Seconds. | ||
|
||
-spec sleep(non_neg_integer()) -> ok. | ||
sleep(Time) when is_integer(Time), Time >= 2000 -> | ||
Deadline = monotonic_time() + Time, | ||
timer:sleep(Time div 1000 - 1), | ||
sleep_until(Deadline); | ||
sleep(Time) when is_integer(Time), Time >= 0 -> | ||
sleep_until(monotonic_time() + Time). | ||
|
||
%%%=================================================================== | ||
%%% Internal functions | ||
%%%=================================================================== | ||
|
||
-spec sleep(non_neg_integer(), integer()) -> ok. | ||
sleep(Time, Start) -> | ||
case monotonic_time() of | ||
Now when Now - Start < Time -> | ||
sleep(Time, Start); | ||
_ -> | ||
-spec sleep_until(integer()) -> ok. | ||
sleep_until(Deadline) -> | ||
case monotonic_time() < Deadline of | ||
true -> | ||
sleep_until(Deadline); | ||
false -> | ||
ok | ||
end. | ||
|
||
-compile({inline, [monotonic_time/0]}). | ||
-spec monotonic_time() -> integer(). | ||
monotonic_time() -> | ||
erlang:monotonic_time(microsecond). |