Created
August 18, 2015 15:12
-
-
Save pichi/36ad9374571905a72d25 to your computer and use it in GitHub Desktop.
StackOverflow question: Best clock or number generator function for concurrency/scalability on Erlang OTP 18?
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
-module(test). | |
-export([bench_all/1, bench/2, bench/3]). | |
-export([ unique_monotonic_integer/0 | |
, update_counter/0 | |
]). | |
iters() -> 1000000. | |
bench_all(N) -> | |
[ {Tag, bench(F, N)} | |
|| {Tag, F} <- | |
[ {unique_monotonic_integer, unique_monotonic_integer()} | |
, {update_counter, update_counter()} | |
, {monotonic_time, fun erlang:monotonic_time/0} | |
, {system_time, fun erlang:system_time/0} | |
, {os_system_time, fun os:system_time/0} | |
, {universal_time, fun calendar:universal_time/0} | |
] | |
]. | |
bench(F, N) -> | |
bench(F, N, iters()). | |
bench(F, N, Iters) when | |
is_function(F, 0), | |
is_integer(N), N > 0, | |
is_integer(Iters), Iters > N -> | |
Loops = Iters div N, | |
Parent = self(), | |
G = fun() -> | |
Pids = [ spawn_link(fun() -> | |
loop(F, Loops), | |
Parent ! self() | |
end) | |
|| _ <- lists:seq(1, N) ], | |
[ receive Pid -> ok end || Pid <- Pids ] | |
end, | |
L = [ element(1, timer:tc(G)) || _ <- lists:seq(1, 10) ], | |
[ _, A, _, _, _, _, _, _, B, _ ] = lists:sort(L), | |
{ A, B }. | |
loop(_, 0) -> ok; | |
loop(F, N) -> F(), loop(F, N-1). | |
unique_monotonic_integer() -> | |
fun() -> erlang:unique_integer([monotonic]) end. | |
update_counter() -> | |
T = ets:new(?MODULE, [public, set]), | |
ets:insert(T, {counter, 0}), | |
fun() -> ets:update_counter(T, counter, {2,1}) end. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment