c java php 语言性能对比
由 admin 发表于 15:37同一台服务器测试
C 0.04 秒
Java 0.21 秒
PHP 2.06 秒
由此可算出 C 是 java性能的5倍,Java 是 PHP 性能的10倍
C
#include <stdio.h> #include <sys/time.h> #define BAILOUT 16 #define MAX_ITERATIONS 1000 int mandelbrot(double x, double y) { double cr = y - 0.5; double ci = x; double zi = 0.0; double zr = 0.0; int i = 0; while(1) { i ++; double temp = zr * zi; double zr2 = zr * zr; double zi2 = zi * zi; zr = zr2 - zi2 + cr; zi = temp + temp + ci; if (zi2 + zr2 > BAILOUT) return i; if (i > MAX_ITERATIONS) return 0; } } int main (int argc, const char * argv[]) { struct timeval aTv; gettimeofday(&aTv, NULL); long init_time = aTv.tv_sec; long init_usec = aTv.tv_usec; int x,y; for (y = -39; y < 39; y++) { printf("\n"); for (x = -39; x < 39; x++) { int i = mandelbrot(x/40.0, y/40.0); if (i==0) printf("*"); else printf(" "); } } printf ("\n"); gettimeofday(&aTv,NULL); double query_time = (aTv.tv_sec - init_time) + (double)(aTv.tv_usec - init_usec)/1000000.0; printf ("C Elapsed %0.2f\n", query_time); return 0; }
Java
import java.util.*; class Mandelbrot { static int BAILOUT = 16; static int MAX_ITERATIONS = 1000; private static int iterate(float x, float y) { float cr = y-0.5f; float ci = x; float zi = 0.0f; float zr = 0.0f; int i = 0; while (true) { i++; float temp = zr * zi; float zr2 = zr * zr; float zi2 = zi * zi; zr = zr2 - zi2 + cr; zi = temp + temp + ci; if (zi2 + zr2 > BAILOUT) return i; if (i > MAX_ITERATIONS) return 0; } } public static void main(String args[]) { Date d1 = new Date(); int x,y; for (y = -39; y < 39; y++) { System.out.print("\n"); for (x = -39; x < 39; x++) { if (iterate(x/40.0f,y/40.0f) == 0) System.out.print("*"); else System.out.print(" "); } } Date d2 = new Date(); long diff = d2.getTime() - d1.getTime(); System.out.println("\nJava Elapsed " + diff/1000.0f); } }
PHP
<?php define("BAILOUT",16); define("MAX_ITERATIONS",1000); class Mandelbrot { function Mandelbrot() { $d1 = microtime(1); for ($y = -39; $y < 39; $y++) { echo("\n"); for ($x = -39; $x < 39; $x++) { if ($this->iterate($x/40.0,$y/40.0) == 0) echo("*"); else echo(" "); } } $d2 = microtime(1); $diff = $d2 - $d1; printf("\nPHP Elapsed %0.2f", $diff); } function iterate($x,$y) { $cr = $y-0.5; $ci = $x; $zi = 0.0; $zr = 0.0; $i = 0; while (true) { $i++; $temp = $zr * $zi; $zr2 = $zr * $zr; $zi2 = $zi * $zi; $zr = $zr2 - $zi2 + $cr; $zi = $temp + $temp + $ci; if ($zi2 + $zr2 > BAILOUT) return $i; if ($i > MAX_ITERATIONS) return 0; } } } $m = new Mandelbrot(); ?>