ets 到底有多快

R13B的支持ets的并发写,{write_concurrency,bool()} Performance tuning. Default is false, which means that the table is optimized towards concurrent read access. An operation that mutates (writes to) the table will obtain exclusive access, blocking any concurrent access of the same table until finished. If set to true, the table is optimized towards concurrent write access. Different parts of the same table can be mutated (and read) by concurrent processes. This is achieve to some degree at the expense of single access and concurrent reader performance. Table typ ordered_set is not affected by this option in current implementation.

我们来测试下这个性能:
root@nd-desktop:~# cat ets_test.erl
-module(ets_test).
-export([new/0, test_insert/2, test_lookup/2, test_update/2]).

new()->
    ets:new(?MODULE, [public, {write_concurrency, true}]).

test_insert(E, N)->
    Start = erlang:now(),
    dotimes(N, fun (I) -> ets:insert(E, {I, hello}) end),
    Stop = erlang:now(),
    N / time_diff(Start, Stop).

test_lookup(E, N)->
    Start = erlang:now(),
    dotimes(N, fun (I) -> ets:lookup(E, I) end),
    Stop = erlang:now(),
    N / time_diff(Start, Stop).

test_update(E, N)->
    Start = erlang:now(),
    P = self(),
    spawn(fun ()->
                  dotimes(N, fun (I) -> ets:insert(E, {I, hello}) end),
                  P!done
          end),

    dotimes(N, fun (I) -> ets:insert(E, {I, hello}) end),

%% /*2个进程一起写 要比一个要快哦*/


    receive X -> X end,

    Stop = erlang:now(),
    N / time_diff(Start, Stop).

dotimes(0, _) -> done;
dotimes(N, F) ->
    F(N),
    dotimes(N - 1, F).

time_diff({A1,A2,A3}, {B1,B2,B3}) ->
    (B1 - A1) * 1000000 + (B2 - A2) + (B3 - A3) / 1000000.0 .


root@nd-desktop:~# erl -smp disable +h 9999999
Erlang R13B01 (erts-5.7.2) [source] [rq:1] [async-threads:0] [hipe] [kernel-poll:false]

Eshell V5.7.2  (abort with ^G)
1>  E = ets_test:new().             
16397
2> ets_test:test_insert(E, 1000000).
855202.2809955239
3>  ets_test:test_lookup(E, 1000000).
1584148.3776736464
4>  ets_test:test_update(E, 1000000).
1068965.36979788
5> ets:info(E, size).
1000000

^Croot@nd-desktop:~# erl +h 9999999            
Erlang R13B01 (erts-5.7.2) [source] [smp:2:2] [rq:2] [async-threads:0] [hipe] [kernel-poll:false]

Eshell V5.7.2  (abort with ^G)
1> E = ets_test:new(). 
16397
2> 
2> ets_test:test_insert(E, 1000000).
673841.2793820066
3> ets_test:test_lookup(E, 1000000).
1250201.595007195
4> ets_test:test_update(E, 1000000).
896912.4685183724 
5> ets:info(E, size).
1000000

可以看到ets的插入和查询操作基本上是在1us左右的级别,相对于process dict的几十ns, 还是差别很大的,因为ets要用2把锁, 一把保护meta table, 一把保护数据表,锁是系统的读写锁。所以这个开销是不容忽视的。

结论: 相比于无锁的数据结构, ets不是非常的快,不过对于一般的应用是够的。

你可能感兴趣的:(数据结构,erlang,F#,Access,performance)