Search code examples
phpperformanceimagemathprocessor

Why can't one do image processing with PHP?


I'm doing basic pixel-by-pixel processing on a 500x500px image. Regardless of what equation I put in, if it doesn't run out of memory, it does it in a awful amount of time.

Compare this script:

define('STARTED_AT',microtime(true));
set_time_limit(0);

function calculatesomething(){ return abs(100-round(pow(15/150,2)))+pow(2,4) - calculatesomething2(); }
function calculatesomething2(){ return abs(100-round(pow(15/150,2)))+pow(2,4) - calculatesomething3(); }
function calculatesomething3(){ return abs(100-round(pow(15/150,2)))+pow(2,4); }

$r = array();
foreach(range(1,pow(10,5)) as $x){
    foreach(range(1,4) as $y)
        $r[] = calculatesomething();
}

$o = (microtime(true)-STARTED_AT);
echo 'took '.$o.'ms to finish';

took 38.847129106522s to finish

And this one:

define('STARTED_AT',microtime(true));
set_time_limit(0);

function calculatesomething(){ return abs(100-round(pow(15/150,2)))+pow(2,4) - calculatesomething2(); }
function calculatesomething2(){ return abs(100-round(pow(15/150,2)))+pow(2,4) - calculatesomething3(); }
function calculatesomething3(){ return abs(100-round(pow(15/150,2)))+pow(2,4); }

$r = array();
foreach(range(1,pow(10,5)) as $x){
    $r[] = abs(100-round(pow(15/150,2)))+pow(2,4) - ( abs(100-round(pow(15/150,2)))+pow(2,4) - ( abs(100-round(pow(15/150,2)))+pow(2,4) ));
    $r[] = abs(100-round(pow(15/150,2)))+pow(2,4) - ( abs(100-round(pow(15/150,2)))+pow(2,4) - ( abs(100-round(pow(15/150,2)))+pow(2,4) ));
    $r[] = abs(100-round(pow(15/150,2)))+pow(2,4) - ( abs(100-round(pow(15/150,2)))+pow(2,4) - ( abs(100-round(pow(15/150,2)))+pow(2,4) ));
    $r[] = abs(100-round(pow(15/150,2)))+pow(2,4) - ( abs(100-round(pow(15/150,2)))+pow(2,4) - ( abs(100-round(pow(15/150,2)))+pow(2,4) ));
}

$o = (microtime(true)-STARTED_AT);
echo 'took '.$o.'ms to finish';

took 29.651962041855s to finish

Only hard-coded the nested iteration and extra function calls and gained 9 ms. I have a 2.4GHz dual-core and 4GB of RAM; shouldn't things run different? What can I do to improve PHP's calculation power?


Solution

  • One CAN do image processing with PHP - I do it frequently and suits my requirements oh so sweet.

    It all depends what your space and time constraints are.

    If doing it in PHP on a server via a browser request does not cut it then you need to review your algorithms and then your tools.

    You have many options but you need to give a real use case before anyone can guide you.