前面測了三者的IO速度,如今來測測它們的函數遞歸調用的速度,這裏的測試方案是使用斐波那契數列最低效的遞歸寫法來進行測試,首先測試文件包含1-32的全部整數。java
fibonacci.awk:shell
#!/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 awkcode
awk time cost = 5s遞歸
awk test overci
test for cinput
c time cost = 0.070000sio
c test overfunction
test for java
Java time cost = 0.044s
java test over
在遞歸調用這方面Java竟然比c還快,比較讓人驚訝