PHP socket connection consuming 100% CPU usage
As part of a recent project for a client, one of the requirements was to create a script that would run ALL day long, and listen for real-time incoming data through a socket connection.
The script itself was a pain for me to write since I wasn't very experienced in working sockets in PHP to begin with.
I finally got everything working and the script was working like a charm but when I would run the script, the CPU usage on the server would jump up to 100%.
After some hair pulling and research (Google), I came across a great tip. While you're listening for data in your socket connection loop, have it sleep after every iteration through the loop in order to let the CPU "rest".
Here's a stripped down version of my code:
$connection = fsockopen($ip, $port, $errno, $errstr, 30);
stream_set_blocking($connection, false);
stream_set_timeout($connection,65);
$info = stream_get_meta_data($connection);
while($connection && !$info['timed_out'] && !feof($connection)) {
$data = fgets($connection);
// Do whatever you need to do with the $data
usleep(500);
}
Notice the call to usleep(500) in the code. This solved my CPU usage problem and only halts the script for 500 micro seconds (A micro second is one millionth of a second).
On average the script now only consumes about 1-2% CPU usage throughout the day. Hope this helps someone in the same situation.
Comments (0)
Leave a comment