Skip to content

Instantly share code, notes, and snippets.

@yjh0502
Last active March 4, 2016 00:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yjh0502/ecb9c899fbbb020b4e33 to your computer and use it in GitHub Desktop.
Save yjh0502/ecb9c899fbbb020b4e33 to your computer and use it in GitHub Desktop.
simple epgsql bench
-module(epgsql_bench).
-export([run/2]).
-define(HOST, "").
-define(PORT, "").
-define(USER, "").
-define(PW, "").
-define(DB, "").
run(N, QueueLen) ->
Ref = epgsqla:connect(?HOST, ?USER, ?PW, [{database, ?DB}, {port, ?PORT}]),
{C, Ref, connected} = receive A -> A end,
{Time, _} = timer:tc(fun() ->
loop(C, N, QueueLen)
end),
io:format("~p ~p ops/s~n", [Time, N * 1000000 / Time]),
epgsqla:close(C),
ok.
loop(C, N, QueueLen) ->
send(C, QueueLen),
loop(C, N, QueueLen, 0).
loop(_C, N, N, N) ->
ok;
loop(C, N, Sent, Recv) ->
RecvCount = recv(),
SendCount = min(N-Sent, RecvCount),
send(C, SendCount),
loop(C, N, Sent + SendCount, Recv + RecvCount).
send(_C, 0) ->
ok;
send(C, N) ->
send(C),
send(C, N-1).
send(C) ->
Name = base64:encode(crypto:strong_rand_bytes(10)),
epgsqla:parse(C, Name, <<"select 1">>, []).
recv() ->
recv_stmt(0, 1000).
recv_stmt(Count, Timeout) ->
receive
{C, _, {ok, {statement, _, _, _} = Stmt}} ->
epgsqla:equery(C, Stmt, []),
recv_stmt(Count, 1000);
_Resp ->
recv_stmt(Count+1, 0)
after Timeout ->
Count
end.
@yjh0502
Copy link
Author

yjh0502 commented Mar 4, 2016

Revised version with prepared_query/3

-module(epgsql_bench).

-export([run/2]).

-define(HOST, "localhost").
-define(PORT, 5432).
-define(USER, "").
-define(PW, "").
-define(DB, "").

run(N, QueueLen) ->
    Ref = epgsqla:connect(?HOST, ?USER, ?PW, [{database, ?DB}, {port, ?PORT}]),
    {C, Ref, connected} = receive A -> A end,
    {Time, _} = timer:tc(fun() ->
        loop(C, N, QueueLen)
    end),
    io:format("~p ~p ops/s~n", [Time, N * 1000000 / Time]),
    epgsqla:close(C),
    ok.

loop(C, N, QueueLen) ->
    {ok, Stmt} = prepare(C),
    send(C, Stmt, QueueLen),
    loop(C, Stmt, N, QueueLen, 0).

loop(_C, _Stmt, N, N, N) ->
    ok;
loop(C, Stmt, N, Sent, Recv) ->
    RecvCount = recv(),
    SendCount = min(N-Sent, RecvCount),
    send(C, Stmt, SendCount),
    loop(C, Stmt, N, Sent + SendCount, Recv + RecvCount).

prepare(C) ->
    Name = base64:encode(crypto:strong_rand_bytes(10)),
    epgsqla:parse(C, Name, <<"select 1">>, []),
    receive
        {C, _, {ok, {statement, _, _, _} = Stmt}} ->
            {ok, Stmt}
    end.

send(_C, _Stmt, 0) ->
    ok;
send(C, Stmt, N) ->
    epgsqla:prepared_query(C, Stmt, []),
    send(C, Stmt, N-1).

recv() ->
    recv_stmt(0, 1000).

recv_stmt(Count, Timeout) ->
    receive
        _Resp ->
            recv_stmt(Count+1, 0)
    after Timeout ->
        Count
    end.

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