参考: [url]http://weblambdazero.blogspot.com/2008/08/mapreduce-in-erlang.html[/url]
MapReduce的主要原理是将一个数据集上的计算分发到许多单独的进程上(map),然后收集它们的结果(reduce)。
在Erlang里实现MapReduce非常细节也十分简单,例如Erlang的作者Joe Armstrong发表了一段代码来表示MapReduce版本的Erlang标准lists:map/2方法:
pmap.erl
[code]
-module(pmap).
-export([pmap/2]).
pmap(F, L) ->
S = self(),
Pids = lists:map(fun(I) ->
spawn(fun() -> do_fun(S, F, I) end)
end, L),
gather(Pids).
gather([H|T]) ->
receive
{H, Result} -> [Result|gather(T)]
end;
gather([]) ->
[].
do_fun(Parent, F, I) ->
Parent ! {self(), (catch F(I))}.
[/code]
pmap的原理也很简单,对List的每项元素的Fun调用都spawn一个process来实际处理,然后再调用gather来收集结果。
如此简洁的代码就实现了基本的MapReduce,不得不服Erlang!
下面是一个fib的示例调用:
fib.erl
[code]
-module(fib).
-export([fib/1]).
fib(0) -> 0;
fib(1) -> 1;
fib(N) when N > 1 -> fib(N-1) + fib(N-2).
[/code]
编译好之后比较一下lists:map/2和pmap:pmap/2的执行效率:
[code]
Eshell > L = lists:seq(0,35).
Eshell > lists:map(fun(X) -> fib:fib(X) end, L).
Eshell > pmap:pmap(fun(X) -> fib:fib(X) end, L).
[/code]
测试结果lists:map执行时间大概4s,pmap:pmap执行时间大概2s,节约了一半的时间,呵呵。
MapReduce的主要原理是将一个数据集上的计算分发到许多单独的进程上(map),然后收集它们的结果(reduce)。
在Erlang里实现MapReduce非常细节也十分简单,例如Erlang的作者Joe Armstrong发表了一段代码来表示MapReduce版本的Erlang标准lists:map/2方法:
pmap.erl
[code]
-module(pmap).
-export([pmap/2]).
pmap(F, L) ->
S = self(),
Pids = lists:map(fun(I) ->
spawn(fun() -> do_fun(S, F, I) end)
end, L),
gather(Pids).
gather([H|T]) ->
receive
{H, Result} -> [Result|gather(T)]
end;
gather([]) ->
[].
do_fun(Parent, F, I) ->
Parent ! {self(), (catch F(I))}.
[/code]
pmap的原理也很简单,对List的每项元素的Fun调用都spawn一个process来实际处理,然后再调用gather来收集结果。
如此简洁的代码就实现了基本的MapReduce,不得不服Erlang!
下面是一个fib的示例调用:
fib.erl
[code]
-module(fib).
-export([fib/1]).
fib(0) -> 0;
fib(1) -> 1;
fib(N) when N > 1 -> fib(N-1) + fib(N-2).
[/code]
编译好之后比较一下lists:map/2和pmap:pmap/2的执行效率:
[code]
Eshell > L = lists:seq(0,35).
Eshell > lists:map(fun(X) -> fib:fib(X) end, L).
Eshell > pmap:pmap(fun(X) -> fib:fib(X) end, L).
[/code]
测试结果lists:map执行时间大概4s,pmap:pmap执行时间大概2s,节约了一半的时间,呵呵。
本文介绍如何使用Erlang实现MapReduce的基本原理及应用示例。通过简洁的代码展示了并行处理列表中每个元素的过程,并对比了并行与非并行方式执行效率的区别。
2667

被折叠的 条评论
为什么被折叠?



