awk, c, java 的函数递归调用速度测试

喜欢而已 提交于 2019-12-17 00:12:20

【推荐】2019 Java 开发者跳槽指南.pdf(吐血整理) >>>

前面测了三者的IO速度,现在来测测它们的函数递归调用的速度,这里的测试方案是使用斐波那契数列最低效的递归写法来进行测试,首先测试文件包含1-32的所有整数。

fibonacci.awk:

#!/bin/awk -f
function fib(n){
        if(n<=2){
                return 1;
        }
        else{
                return fib(n-2)+fib(n-1);
        }
}
BEGIN{
        start = systime();
}
{
        fb = fib($1);
#       print fb;
}
END{
        end = systime();
        printf("awk time cost = %ds\n",end-start)
}

fibonacci.c:

#include<stdio.h>
#include<time.h>
int fib(int n){
        if (n<=2)       return 1;
        return fib(n-1)+fib(n-2);
}
main(){
        FILE *fp = fopen("fib.in","r");
        int n;
        long start = clock();
        while(fscanf(fp,"%d",&n)!=EOF){
                int fn = fib(n);
//              printf("fib(%d) = %d\n",n,fn);
        }
        long end = clock();
        printf("c time cost = %lfs\n",1.0*(end-start)/CLOCKS_PER_SEC);
}
fibonacci.java:

import java.util.*;
import java.io.*;
public class fibonacci{
        public static int fib(int n){
                if(n <= 2)      return 1;
                else    return fib(n-1)+fib(n-2);
        }
        public static void main(String[] args){
                Scanner in;
                try{
                        in = new Scanner(new FileInputStream(new File("fib.in")));
                }catch(Exception e){
                        System.out.println("open file error,now the input is \"System.in\"\n");
                        in = new Scanner(System.in);
                }
                long start = System.currentTimeMillis();
                while(in.hasNext()){
                        int n = in.nextInt();
                        int res = fib(n);
//                      System.out.println(res);
                }
                long end = System.currentTimeMillis();
                System.out.println("Java time cost = "+1.0*(end-start)/1000+"s");
        }
}
执行脚本test.sh:

#!/bin/sh

echo "test for awk"
./fibonacci.awk fib.in
echo "awk test over\n"

echo "test for c"
gcc fibonacci.c -o fibonacci
./fibonacci
echo "c test over\n"

echo "test for java"
javac fibonacci.java
java fibonacci
echo "java test over\n"

运行结果:

 test for awk

awk time cost = 5s

awk test over

 

test for c

c time cost = 0.070000s

c test over

 

test for java

Java time cost = 0.044s

java test over

 

在递归调用这方面Java居然比c还快,比较让人惊讶

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!