Chinaunix首页 | 论坛 | 博客
  • 博客访问: 4971520
  • 博文数量: 921
  • 博客积分: 16037
  • 博客等级: 上将
  • 技术积分: 8469
  • 用 户 组: 普通用户
  • 注册时间: 2006-04-05 02:08
文章分类

全部博文(921)

文章存档

2020年(1)

2019年(3)

2018年(3)

2017年(6)

2016年(47)

2015年(72)

2014年(25)

2013年(72)

2012年(125)

2011年(182)

2010年(42)

2009年(14)

2008年(85)

2007年(89)

2006年(155)

分类: Erlang

2016-04-17 10:52:51

MapReduce的主要原理是将一个数据集上的计算分发到许多单独的进程上(map),然后收集它们的结果(reduce)。

在Erlang里实现MapReduce非常细节也十分简单,例如Erlang的作者Joe Armstrong发表了一段代码来表示MapReduce版本的Erlang标准lists:map/2方法: 

  1. -module(pmap).
  2. -export([pmap/2]).
  3.   
  4. pmap(F, L) ->
  5.   S = self(),
  6.   Pids = lists:map(fun(I) ->
  7.     spawn(fun() -> do_fun(S, F, I) end)
  8.   end, L),
  9.   gather(Pids).
  10.   
  11. gather([H|T]) ->
  12.   receive
  13.     {H, Result} -> [Result|gather(T)]
  14.   end;
  15. gather([]) ->
  16.   [].
  17.   
  18. do_fun(Parent, F, I) ->
  19.     Parent ! {self(), (catch F(I))}.
pmap的原理也很简单,对List的每项元素的Fun调用都spawn一个process来实际处理,然后再调用gather来收集结果。 

如此简洁的代码就实现了基本的MapReduce,不得不服Erlang! 

下面是一个fib的示例调用: 
fib.erl 

  1. -module(fib).
  2. -export([fib/1]).
  3.   
  4. fib(0) -> 0;
  5. fib(1) -> 1;
  6. fib(N) when N > 1 -> fib(N-1) + fib(N-2).

编译好之后比较一下lists:map/2和pmap:pmap/2的执行效率: 


  1. Eshell > L = lists:seq(0,35).
  2. Eshell > lists:map(fun(X) -> fib:fib(X) end, L).
  3. Eshell > pmap:pmap(fun(X) -> fib:fib(X) end, L).


测试结果lists:map执行时间大概4s,pmap:pmap执行时间大概2s,节约了一半的时间。

原文来自:http://www.cnblogs.com/orez88/articles/1787119.html


阅读(1655) | 评论(0) | 转发(0) |
0

上一篇:python中的reduce

下一篇:Erlang里实现MapReduce

给主人留下些什么吧!~~