Erlang常用代码段
十六进制字符串转为二进制
hex_to_bin(Bin) ->
hex2bin(Bin). hex2bin(Bin) when is_binary(Bin) ->
hex2bin(binary_to_list(Bin));
hex2bin([]) ->
<<>>;
hex2bin([X, Y | Rest]) ->
<<(erlang:list_to_integer([X], 16) * 16 + erlang:list_to_integer([Y], 16)):8, (hex2bin(Rest))/binary>>.
二进制转为十六进制字符串
bin2hex(B) ->
bin2hex(B, lower). bin2hex(B, LowerOrUpper) when is_binary(B) ->
bin2hex(binary_to_list(B), LowerOrUpper);
bin2hex(L, upper) ->
LH0 = lists:map(fun(X) -> erlang:integer_to_list(X, 16) end, L),
LH = lists:map(fun([X, Y]) -> [X, Y]; ([X]) -> [$0, X] end, LH0),
lists:flatten(LH);
bin2hex(B, lower) ->
H = bin2hex(B, upper),
string:to_lower(H).
反编译代码
有时候线上出问题的时候,需要查看线上运行的代码,这时候就用到反编译了。
decompile(Mod) ->
{ok, {_, [{abstract_code, {_, AC}}]}} = beam_lib:chunks(code:which(Mod), [abstract_code]),
try
io:format("~s~n", [erl_prettypr:format(erl_syntax:form_list(AC))])
catch
io:format("~ts~n", [erl_prettypr:format(erl_syntax:form_list(AC))])
end.
分裂进程
erlang分裂进程的函数是erlang:spawn。选项有spawn(Fun) -> pid()
spawn(Node, Fun) -> pid() %如果Node不存在,返回一个无用的pid
spawn(Module, Function, Args) -> pid()
spawn(Node, Module, Function, Args) -> pid()
spawn_link(Fun) -> pid()
spawn_link(Node, Fun) -> pid()
spawn_link(Module, Function, Args) -> pid()
spawn_link(Node, Module, Function, Args) -> pid()
spawn_monitor(Fun) -> {pid(), reference()}
spawn_monitor(Module, Function, Args) -> {pid(), reference()}
spawn_opt(Fun, Options) -> pid() | {pid(), reference()}
spawn_opt(Node, Fun, Options) -> pid() | {pid(), reference()}
spawn_opt(Module, Function, Args, Options) -> pid() | {pid(), reference()}
spawn_opt(Node, Module, Function, Args, Options) -> pid() | {pid(), reference()}
Options = [Option]
Option =
link |
monitor |
{priority, Level :: priority_level()} |
{fullsweep_after, Number :: integer() >= 0} |
{min_heap_size, Size :: integer() >= 0} |
{min_bin_vheap_size, VSize :: integer() >= 0}
priority_level() = low | normal | high | max
+ link: 父进程与子进程建立连接
+ monitor: 父进程监控子进程
+ {priority, Level}: 设置新的进程的优先级。等价于在新进程中执行process_flag(priority, Level)。区别在于,spawn的时候设置优先级,优先级会在进程被选择运行之前就设置好了。
+ {fullsweep_after, Number}:只是用在调整性能上。Erlang的运行系统,使用的是分代的垃圾回收机制。用一个『old heap』保存至少存活了一个垃圾回收周期的数据,当old heap空间不够时,就会执行垃圾回收。
+ {min_heap_size, Size},只是用在调整性能上。设置heap的最小size,单位是word。将这个值设置的比系统默认的大的话,会加速一些进程运行,因为会减少垃圾回收的执行次数。但是太大会导致内存不够,减慢系统运行。
+ {min_bin_vheap_size, VSize},只是用在调整性能上。
+ 交叉引用工具:xref。xref通过分析函数的调用和定义,发现函数、模块、应用和版本之间的依赖关系。这个工具可以帮助查看是否有函数名输入错误。在用rebar打包时,可以用rebar xref执行。
+ 获得ps命令得到的消耗的内存
```erlang
get_ps_real_memory() ->
Cmd = "pid=`echo $$`;p=`ps -ef | awk -v pid=$pid '$2 == pid {print $3}'`;mem=`ps -o rss -p $p | grep -v RSS`;r=$(($mem/1024));echo $r",
os:cmd(Cmd),
Result = os:cmd(Cmd),
string:substr(Result, 1, length(Result) - 1).
```
+ 获得top命令得到的消耗的内存
```erlang
get_top_real_memory() ->
Cmd = "pid=`echo $$`;p=`ps -ef | awk -v pid=$pid '$2 == pid {print $3}'`;mem=`cat /proc/$p/stat | awk '{print $24}'`;r=$(($mem*4096/1024/1024));echo $r",
Result = os:cmd(Cmd),
case length(Result) > 1 of
true ->
string:substr(Result, 1, length(Result) -1);
false ->
0
end.
```
+ 获得当前cpu的核数
```erlang
get_cpu_count() ->
Cmd = "cat /proc/cpuinfo | grep processor | wc -l",
R = os:cmd(Cmd),
case string:to_integer(R) of
{Count, _} when is_integer(Count) -> Count;
{error, _} -> 0
end.
```
+ 获得ps命令得到的虚拟内存消耗
```erlang
get_ps_virtual_memory() ->
Cmd = "pid=`echo $$`;p=`ps -ef | awk -v pid=$pid '$2 == pid {print $3}'`;mem=`ps -o vsz -p $p | grep -v VSZ`;r=$(($mem/1024));echo $r",
Result = os:cmd(Cmd),
string:substr(Result, 1, length(Result) - 1).
```
+获得top命令得到的虚拟内存消耗
```erlang
get_top_virtual_memory() ->
Cmd = "pid=`echo $$`;p=`ps -ef | awk -v pid=$pid '$2 == pid {print $3}'`;mem=`cat /proc/$p/stat | awk '{print $24}'`;r=$(($mem*4096/1024/1024));echo $r",
Result = os:cmd(Cmd),
case length(Result) > 1 of
true ->
string:substr(Result, 1, length(Result) - 1);
false ->
0
end.
```
+ 获得erlang运行时的进程信息
```erlang
process_infos() ->
filelib:ensure_dir("./log/"),
File = "./log/processes_infos.log",
{ok, Fd} = file:open(File, [write, raw, binary, append]),
Fun = fun(Pi) ->
Info = io_lib:format("=>~p \n\n",[Pi]),
case filelib:is_file(File) of
true -> file:write(Fd, Info);
false ->
file:close(Fd),
{ok, NewFd} = file:open(File, [write, raw, binary, append]),
file:write(NewFd, Info)
end,
timer:sleep(20)
end,
[Fun(erlang:process_info(P)) || P <- erlang:processes()].
- eralng gen_server:call
这是一个同步调用,pid1通过erlang:send()发送给pid2消息后,receive等待返回,这时候pid1处于阻塞状态。pid2是一个gen_server行为模式的进程,loop函数接收到消息后,进行相应处理,并返回。
- gen_server:cast
直接用erlang:send发送'$gen_cast'消息。
Erlang常用代码段的更多相关文章
- PyTorch常用代码段整理合集
PyTorch常用代码段整理合集 转自:知乎 作者:张皓 众所周知,程序猿在写代码时通常会在网上搜索大量资料,其中大部分是代码段.然而,这项工作常常令人心累身疲,耗费大量时间.所以,今天小编转载了知乎 ...
- Java常用代码段 - 未完待续
记录一些自己写项目常用的代码段. 格式化常用日期格式 Date date = new Date(System.currentTimeMillis()); DateFormat d3 = DateFor ...
- PyTorch 常用代码段整理
基础配置 检查 PyTorch 版本 torch.__version__ # PyTorch version torch.version.cuda ...
- JavaScript常用代码段
总结一下在各种地方看到的还有自己使用的一些实用代码 1)区分IE和非IE浏览器 if(!+[1,]){ alert("这是IE浏览器"); } else{ alert(" ...
- C#获取本地IP地址[常用代码段]
获得当前机器的IP代码,假设本地主机为单网卡 string strHostName = Dns.GetHostName(); //得到本机的主机名 IPHostEntry ipEntry = Dns. ...
- php常用代码段
点击换验证码 <a href=" src="{:U('Reglog/vcode')}" /></a> TP上一条下一条 $prev=$artica ...
- SQL常用代码段
--STUFF 函数将字符串插入另一字符串.它在第一个字符串中从开始位置删除指定长度的字符:然后将第二个字符串插入第一个字符串的开始位置. STUFF ( character_expression , ...
- PHP常用代码段:
1.PHP加密解密 function encryptDecrypt($key, $string, $decrypt){ if($decrypt){ $decrypted ...
- php 常用代码段
1.写文件 $fp = fopen("jsapi_ticket.json", "w+"); fwrite($fp, $str); fclose($fp); 2. ...
随机推荐
- Centos 6.5下一个SNMP简单配置(snmp protocol v3,监控宝)
Centos 6.5下一个SNMP简单配置(snmp protocol v3.监控宝) jom_ch@2014/7/25 1,安装 >yum -y install net-snmp net-sn ...
- 它们的定义UIAlertView
code4App有很多伟大的上方UI特效代码,,好牛逼啊,这效果,太炫了,哇,怎么自己写不出来.事实上,再炫的特效,都是依据苹果系统的框架而来,假设我们了解系统框架实现的原理,也就能写出属于自己自己定 ...
- unity3D实际的原始视频游戏开发系列讲座10它《战斗:外来入侵》在第一季度游戏开发
解说文件夹 <保卫战:异形入侵>游戏开发 第一讲 游戏演示和资源的介绍 第二讲 "异形"怪物的实现 第三讲 "异形"怪物生命值的体现 第四讲 ...
- NSIS:判断并安装.NET Framework 4 的例子
原文 NSIS:判断并安装.NET Framework 4 的例子 现在.NET开发的软件已经大行其道,但有些操作系统并不符合软件的运行要求,所以,我们需要在安装程序中进行.NET Framework ...
- Cordic 算法之 反正切
在通信的算法中,常采用Cordic算法之一,知道角度产生正交的的正弦余弦, 或者知道正弦和余弦求角度,求反正切. 1. 求正弦和余弦值. 方法:旋转角度,得到正弦余弦值: 再旋转角度,到达下一个正弦余 ...
- Android Notification (转)
上回我们提到在4.0ICS之后,Google为Android平台的Notification这把“倚天剑”注入了更多新鲜的元素,使其更加实用美观.Notification的样式从此变得丰富起来,以适应于 ...
- printf交替使用
今天附带printf一些替代实现. 转载请注明出处:http://blog.csdn.net/u010484477谢谢^_^ 我们总是用printf做各种输出语句: printf("%d&q ...
- Mac OS X中报:java.io.UnixFileSystem.createFileExclusively(Native Method)的简单原因
这个博客太简单了!想到可能有其它朋友也遇到这个问题,就记录一下. 今天把一个之前在Windows上的Java项目放到Mac OS X上执行,本来认为应该非常easy的事情,结果还是报: Excepti ...
- 用grunt搭建自动化的web前端开发环境
用grunt搭建自动化的web前端开发环境 jQuery在使用grunt,bootstrap在使用grunt,百度UEditor在使用grunt,你没有理由不学.不用! 1. 前言 各位web前端开发 ...
- How many prime numbers(素数)
Problem Description Give you a lot of positive integers, just to find out how many prime numbers t ...