Skip to content

Instantly share code, notes, and snippets.

@taiyow
Created December 6, 2018 02:14
Show Gist options
  • Save taiyow/6d0dffaf534722eee83c9ccfee3a0a67 to your computer and use it in GitHub Desktop.
Save taiyow/6d0dffaf534722eee83c9ccfee3a0a67 to your computer and use it in GitHub Desktop.
1msのtimerをビジーループで実現
-module(busytimer_test).
-export([test/2]).
-define(MICROSECONDS, 1000000).
test(Wait, Count) ->
Begin = erlang:timestamp(),
busywait_repeat(Wait, Count),
End = erlang:timestamp(),
DiffUsec = timer:now_diff(End, Begin),
DiffSec = DiffUsec / 1000 / 1000,
io:format("~p counts in ~p sec, ~p count/sec~n", [Count, DiffSec, Count/DiffSec]).
busywait_repeat(_Wait, 0) ->
ok;
busywait_repeat(Wait, N) ->
busywait(Wait),
busywait_repeat(Wait, N-1).
busywait(Wait) ->
Finish = erlang:monotonic_time(?MICROSECONDS) + Wait*1000,
busywait_until(Finish).
busywait_until(Finish) ->
Now = erlang:monotonic_time(?MICROSECONDS),
if Now >= Finish -> ok;
true -> busywait_until(Finish)
end.
@taiyow
Copy link
Author

taiyow commented Dec 6, 2018

erl上で以下を実行:

1> c(busytimer_test).
{ok,busytimer_test}
2> busytimer_test:test(1,1000).
1000 counts in 1.003644 sec, 996.3692305239707 count/sec
ok

だいたい秒間1000回になっている。

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