Home > Erlang探索, 源码分析 > 获取binary更详细的信息

获取binary更详细的信息

November 7th, 2013

原创文章,转载请注明: 转载自系统技术非业余研究

本文链接地址: 获取binary更详细的信息

binary数据结构我们用的比较多,效率的高低直接影响了服务器的性能。Erlang官方文档“Constructing and matching binaries” 这个章节 提供了非常详细的高效binary使用的解释。

并且erts内部提供了未公开选项让我们知道更多细节,演示如下:

$ erl
Erlang R15B03 (erts-5.9.3.1) [source] [64-bit] [smp:16:16] [async-threads:0] [hipe] [kernel-poll:false]

Eshell V5.9.3.1  (abort with ^G)
1> erts_debug:set_internal_state(available_internal_state, true).
false

=ERROR REPORT==== 6-Nov-2013::23:55:47 ===
Process <0.31.0> enabled access to the emulator internal state.
NOTE: This is an erts internal test feature and should *only* be used by OTP test-suites.

2> erts_debug:get_internal_state({binary_info, <<1:99999>>}).    
{refc_binary,12500,{binary,25000},3}

3> erts_debug:get_internal_state({binary_info, <<"XYZ">>}).    
{refc_binary,3,{binary,256},3}

那么如何解读返回的值呢?还是上源码吧!

BIF_RETTYPE erts_debug_get_internal_state_1(BIF_ALIST_1)
{
...
                        pb = (ProcBin *) binary_val(real_bin);
                        val = pb->val;
                        (void) erts_bld_uint(NULL, &hsz, pb->size);
                        (void) erts_bld_uint(NULL, &hsz, val->orig_size);
                        hp = HAlloc(BIF_P, hsz);

                        /* Info about the Binary* object */
                        SzTerm = erts_bld_uint(&hp, NULL, val->orig_size);
                        res = TUPLE2(hp, am_binary, SzTerm);
                        hp += 3;

                        /* Info about the ProcBin* object */
                        SzTerm = erts_bld_uint(&hp, NULL, pb->size);
                        res = TUPLE4(hp, AM_refc_binary, SzTerm,
                                     res, make_small(pb->flags));

...
}

从源码可以看出返回值的格式:
proc binary:{refc_binary, pb_size, {binary, orig_size}, pb_flags}
heapbinary:heap_binary

#define PB_IS_WRITABLE 1 /* Writable (only one reference to ProcBin) */
#define PB_ACTIVE_WRITER 2 /* There is an active writer */
其中pb_flags为上面二个标志的组合。

从这些信息我们可以验证binary是会预留部分空间的。

小结:类似这样的未公开获取内部信息还有不少,可以参考这里

祝玩的开心!

Post Footer automatically generated by wp-posturl plugin for wordpress.

  1. November 23rd, 2013 at 22:56 | #1

    效率指南“Constructing and matching binaries”上的例子:
    Bin0 = <>, %% 1
    Bin1 = <>, %% 2
    Bin2 = <>, %% 3
    Bin3 = <>, %% 4
    Bin4 = <>, %% 5 !!!
    {Bin4,Bin3} %% 6
    是不是说第2行Bin1实际上是将Bin0复制到一个预留了空间的的refc bin之后再append后面的1,2,3字节?如果是这样的话,那么Bin1应该就是refc bin了吧?可是在第2行之后运行 io:format(“~p~n”, [erts_debug:get_internal_state({binary_info, Bin1})]), 输出的还是 heap_binary

Comments are closed.