Skip to content

Instantly share code, notes, and snippets.

@physacco
Created March 15, 2013 17:16
Show Gist options
  • Save physacco/5171496 to your computer and use it in GitHub Desktop.
Save physacco/5171496 to your computer and use it in GitHub Desktop.
This is a hello-world HTTP server in Erlang. It is used to test the performance of servers.
-module(ehttpd).
-compile(export_all).
start() ->
start(8888).
start(Port) ->
N = erlang:system_info(schedulers),
listen(Port, N),
io:format("ehttpd ready with ~b schedulers on port ~b~n", [N, Port]),
register(?MODULE, self()),
receive Any -> io:format("~p~n", [Any]) end. %% to stop: ehttpd!stop.
listen(Port, N) ->
Opts = [{active, false},
binary,
{backlog, 256},
{packet, http_bin},
{raw,6,9,<<1:32/native>>}, %defer accept
%%{delay_send,true},
%%{nodelay,true},
{reuseaddr, true}],
{ok, S} = gen_tcp:listen(Port, Opts),
Spawn = fun(I) ->
register(list_to_atom("acceptor_" ++ integer_to_list(I)),
spawn_opt(?MODULE, accept, [S, I], [link, {scheduler, I}]))
end,
lists:foreach(Spawn, lists:seq(1, N)).
accept(S, I) ->
case gen_tcp:accept(S) of
{ok, Socket} -> spawn_opt(?MODULE, loop, [Socket], [{scheduler, I}]);
Error -> erlang:error(Error)
end,
accept(S, I).
loop(S) ->
case gen_tcp:recv(S, 0) of
{ok, http_eoh} ->
Response = <<"HTTP/1.1 200 OK\r\nContent-Length: 12\r\n\r\nhello world!">>,
gen_tcp:send(S, Response),
gen_tcp:close(S),
ok;
{ok, _Data} ->
loop(S);
Error ->
Error
end.

ehttpd benchmark

compile and run

# ulimit -n 20480
# erlc ehttpd.erl
# erl +K true +h 99999 +P 99999 -s ehttpd

benchmark with ab

$ ab -n 10000 -c 100 http://localhost:8888/

ab output

Server Hostname:        127.0.0.1
Server Port:            8888

Document Path:          /
Document Length:        12 bytes

Concurrency Level:      100
Time taken for tests:   1.382 seconds
Complete requests:      10000
Failed requests:        0
Write errors:           0
Total transferred:      511530 bytes
HTML transferred:       120360 bytes
Requests per second:    7234.19 [#/sec] (mean)
Time per request:       13.823 [ms] (mean)
Time per request:       0.138 [ms] (mean, across all concurrent requests)
Transfer rate:          361.38 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    5   1.2      5      10
Processing:     4    9   1.8      8      24
Waiting:        2    7   1.6      6      23
Total:          9   14   2.1     14      29

Percentage of the requests served within a certain time (ms)
  50%     14
  66%     14
  75%     15
  80%     15
  90%     16
  95%     17
  98%     19
  99%     20
 100%     29 (longest request)

platform

  • Intel(R) Core(TM) i3 CPU M 330 @ 2.13GHz
  • 2GB RAM
  • Fedora 12
  • Erlang R13B04 (erts-5.7.5)

references

  1. http://blog.yufeng.info/archives/105
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment