What's slowing for loops/assignment vs. C?

Posted by Lee on Stack Overflow See other posts from Stack Overflow or by Lee
Published on 2010-03-22T06:37:12Z Indexed on 2010/03/22 6:41 UTC
Read the original article Hit count: 686

Filed under:
|
|
|
|

I have a collection of PHP scripts that are extremely CPU intensive, juggling millions of calculations across hundreds of simultaneous users.

I'm trying to find a way to speed up the internals of PHP variable assignment, and looping sequences vs C.

Although PHP is obviously loosely typed, is there any way/extension to specifically assign type (assign, not cast, which seems even more expensive) in a C-style fashion?

Here's what I mean.

This is some dummy code in C:

#include <stdio.h>

int main() {
unsigned long add=0;

for(unsigned long x=0;x<100000000;x++) {
    add = x*59328409238;
}
printf("x is %ld\n",add);

}

Pretty self-explanatory -- it loops 100 million times, multiples each iteration by an arbitrary number of some 59 billion, assigns it to a variable and prints it out.

On my Macbook, compiling it and running it produced:

lees-macbook-pro:Desktop lee$ time ./test2
x is 5932840864471590762

real    0m0.266s
user    0m0.253s
sys  0m0.002s

Pretty darn fast!

A similar script in PHP 5.3 CLI...

<?php
for($i=0;$i<100000000;$i++){
    $a=$i*59328409238;
}
echo $a."\n";
?>

... produced:

lees-macbook-pro:Desktop lee$ time /Applications/XAMPP/xamppfiles/bin/php test3.php
5.93284086447E+18

real    0m22.837s
user    0m22.110s
sys  0m0.078s

Over 22 seconds vs 0.2!

I realize PHP is doing a heck of a lot more behind the scenes than this simple C program - but is there any way to make the PHP internals to behave more 'natively' on primitive types and loops?

© Stack Overflow or respective owner

Related posts about php

Related posts about c