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),
[color=red]
%% /*2个进程一起写 要比一个要快哦*/[/color]

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不是非常的快,不过对于一般的应用是够的。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值