Skip to content

Instantly share code, notes, and snippets.

@kuniyoshi
Created February 26, 2014 17:09
Show Gist options
  • Save kuniyoshi/9233869 to your computer and use it in GitHub Desktop.
Save kuniyoshi/9233869 to your computer and use it in GitHub Desktop.
There is no length/1 optimization. Capture length/1 instead of write code every time.
-module(bench).
-export([run/0]).
-define(SEED, {1393,433335,396007}).
-define(LENGTH, trunc(math:pow(2, 14))).
-define(TIMES, 3).
-include_lib("eunit/include/eunit.hrl").
gen() ->
random:seed(?SEED),
lists:map(fun(_) -> random:uniform() end, lists:duplicate(?LENGTH, 0)).
length_every_time(Nums) ->
[N / length(Nums) || N <- Nums].
length_one_time(Nums) ->
Length = length(Nums),
[N / Length || N <- Nums].
%% 7> bench:run().
%% src/bench.erl:22:<0.38.0>: EveryTime = [602406,692627,1232612]
%% src/bench.erl:24:<0.38.0>: OneTime = [1823,947,2815]
%% ok
run() ->
Nums = gen(),
EveryTime = lists:map(fun({T, _}) -> T end, [timer:tc(fun length_every_time/1, [Nums]) || _ <- lists:seq(1, ?TIMES)]),
?debugVal(EveryTime),
OneTime = lists:map(fun({T, _}) -> T end, [timer:tc(fun length_one_time/1, [Nums]) || _ <- lists:seq(1, ?TIMES)]),
?debugVal(OneTime),
ok.
@kuniyoshi
Copy link
Author

My environment:

--- erlang
Erlang R16B02 (erts-5.10.3) [source] [64-bit] [smp:4:4] [async-threads:10] [hipe] [kernel-poll:false]

Eshell V5.10.3 (abort with ^G)

--- PC
MacBook Air
Processor: 1.7 GHz Intel Core i7
Memory: 8 GB 1600 MHz DDR3

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