实验CPU密集型计算

阅读更多
今天实验了一下霸爷博客里的CPU密集型计算,
计算的内容时计算四遍斐波纳妾数列的第四十个元素是多少
代码如下:
cpu_intensive.erl
-module(cpu_intensive).

-compile([export_all]).

fib_test() ->
	fib(40),
	fib(40),
	fib(40),
	fib(40),
	fib(40).

fib(0) ->
	1;
fib(1) ->
	1;
fib(N) ->
	fib(N-1) + fib(N-2).

cpu_intensive.c
#include"stdio.h"

unsigned int fib(unsigned int n)
{
    if(n ==1 || n == 0){
        return 1;
    }
    return fib(n-1) + fib(n-2);
}


int main()
{
    fib(40);
    fib(40);
    fib(40);
    fib(40);
    fib(40);
    return 0;
}


Makefile文件
引用

all: native normal c

native:
@erlc +native cpu_intensive.erl
@echo ""
@echo "Fibonacci Erlang native code"
@time erl -noshell -s cpu_intensive fib_test -s erlang halt

normal:
@erlc cpu_intensive.erl
@echo ""
@echo "Fibonacco Erlang non-native code"
@time erl -noshell -s cpu_intensive fib_test -s erlang halt

c:
@gcc -O0 -o cpu_intensive cpu_intensive.c
@echo ""
@echo "Fibonacci written in C without optimizations"
@time ./cpu_intensive

结果如下:
$ make

Fibonacci Erlang native code
6.35user 0.02system 0:06.37elapsed 100%CPU (0avgtext+0avgdata 69616maxresident)k
0inputs+0outputs (0major+4039minor)pagefaults 0swaps

Fibonacco Erlang non-native code
29.48user 0.02system 0:29.54elapsed 99%CPU (0avgtext+0avgdata 70352maxresident)k
0inputs+0outputs (0major+4084minor)pagefaults 0swaps

Fibonacci written in C without optimizations
5.54user 0.00system 0:05.55elapsed 99%CPU (0avgtext+0avgdata 1376maxresident)k
0inputs+0outputs (0major+109minor)pagefaults 0swaps


代码可以从附件下载
  • cpu_intensive.tar.gz (3.3 KB)
  • 下载次数: 0

你可能感兴趣的:(erlang,c,time)