Speeding up PHP - Using process forking to accelerate image resizing
07 Oct 2011
Most of my projects at work involve resizing images in PHP applications, usually the result is loaded via AJAX so it needs to be generated as fast as possible for optimum user experience. Recently I discovered the ability to fork processes in PHP, this gives the ability to run multiple functions at the same time. In the example below I’ll demonstrate how parallel processing can be used in PHP to speed the generation of several different sizes of preview images from a large uploaded image.
This code uses the PCNTL extension which was installed as standard on my Ubuntu 11.04 PHP 5.3 install.
Conventionally to generate a couple of different sizes of images from a large JPEG image one might use something like this:
To get an idea of the speed of this script we can run it from the command line:
This takes couple of seconds, as you might expect, in my case:
However rather than performing the resizing sequentially it can be performed in parallel using the same create_preview() function as before:
Now running the script using the same command line again the advantage is instantly noticeable:
As you can see from this very unscientific test running the processes in parallel increases the speed by over 3.5x. As long as you’re careful to watch for threads terminating and not just leaving them unattended this seems like a great way to speed up simple repetitive tasks, I’d certainly hope to find a place for it in some of my applications in the future I’ll probably not use this in a production web application due to the warning that Paul kindly posted below, I guess should read the manual before getting excited…