Tuesday, October 16, 2012

PHP vs Node.js vs Native Speed Comparison

A quick speed comparison between PHP, Node.js and native code. This is obviously an artificial benchmark. The code generates four random numbers between 0 and 100 and uses them as coordinates of two points on a plane, and then calculates the distance between them. This is repeated 10 million times. Only the loop is timed, so process startup time is not part of the timing. The results are:

PHP - 12.692 seconds
Node.js - 0.328 seconds
Native - 0.308 seconds

All tests were run on a MacBook Pro. PHP is almost 40 times slower than Node.js. Node.js is almost as fast as native code, which makes sense since it does just-in-time compilation.

PHP code:
<?php

function distance($x1, $y1, $x2, $y2) {
  $dx = $x2 - $x1;
  $dy = $y2 - $y1;
  return sqrt($dx * $dx + $dy * $dy);
}

$start = microtime(TRUE);
for($i = 0; $i < 10000000; $i++) {
  $x1 = rand(0, 100);
  $x2 = rand(0, 100);
  $y1 = rand(0, 100);
  $y2 = rand(0, 100);
  distance($x1, $y1, $x2, $y2);
}
$stop = microtime(TRUE);

echo "Elapsed time: " . ($stop - $start) . " s\n";

Node.js code:
function distance(x1, y1, x2, y2) {
  var dx = x2 - x1;
  var dy = y2 - y1;
  return Math.sqrt(dx * dx + dy * dy);
}

var start = Date.now()/1000;
for(var i = 0; i < 10000000; i++) {
  x1 = Math.random() * 100;
  x2 = Math.random() * 100;
  y1 = Math.random() * 100;
  y2 = Math.random() * 100;
  distance(x1, y1, x2, y2);
}
var stop = Date.now()/1000;

console.log("Elapsed time: " + (stop - start) + " s\n");

C code, compiled with gcc -Wall:
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <sys/time.h>
#include <math.h>

double distance(double x1, double y1, double x2, double y2) {
  double dx, dy;
  dx = x2 - x1;
  dy = y2 - y1;
  return sqrt(dx * dx + dy * dy);
}

int main(void) {
  int i;
  double x1, x2, y1, y2;
  struct timeval start, stop;

  srand(time(NULL));
  gettimeofday(&start, NULL);
  for(i = 0; i < 10000000; i++) {
    x1 = rand() * 100;
    x2 = rand() * 100;
    y1 = rand() * 100;
    y2 = rand() * 100;
    distance(x1, y1, x2, y2);
  }
  gettimeofday(&stop, NULL);
  printf("Elapsed time: %.3f s\n", (stop.tv_sec-start.tv_sec) + (stop.tv_usec-start.tv_usec) / 1000000.0);
  return 0;
}

No comments: