Programster's Blog

Tutorials focusing on Linux, programming, and open-source

Enable PHP Opcache

PHP

I was profiling one of my services the other day and found that it was spending a noticeable amount of time just including files through require statements. I was able to eliminate almost all of this time by enabling the OPcache, resulting in a noticeable performance boost. I can't imagine a scenario where it is not worth using the OPcache in production, but you probably don't want it enabled in dev unless you turn the validate_timestamps down to something like 1 so that your updates keep going through.

Below are the commands that you would need to run in Ubuntu 16.04 to enable the OPcache for the CLI.

sudo apt install php7.0-opcache
sudo phpenmod opcache


# Enable the opcache.
SEARCH=";opcache.enable=0"
REPLACE="opcache.enable=1"
FILEPATH="/etc/php/7.0/cli/php.ini"
sed -i "s:$SEARCH:$REPLACE:" $FILEPATH

# Enable opcache for the cli
SEARCH=";opcache.enable_cli=0"
REPLACE="opcache.enable_cli=1"
FILEPATH="/etc/php/7.0/cli/php.ini"
sed -i "s:$SEARCH:$REPLACE:" $FILEPATH


# Set the amount of memory we can use for caching.
# The production server has oooooodles of RAM.
SEARCH=";opcache.memory_consumption=64"
REPLACE="opcache.memory_consumption=256"
FILEPATH="/etc/php/7.0/cli/php.ini"
sed -i "s:$SEARCH:$REPLACE:" $FILEPATH


# increase the number of files to cache
SEARCH=";opcache.max_accelerated_files=2000"
REPLACE="opcache.max_accelerated_files=1000000"
FILEPATH="/etc/php/7.0/cli/php.ini"
sed -i "s:$SEARCH:$REPLACE:" $FILEPATH


# Don't bother revalidating files for a long time because
# they should never change.
# Obviously you need to undo this in dev.
SEARCH=";opcache.validate_timestamps=1"
REPLACE="opcache.validate_timestamps=3000"
FILEPATH="/etc/php/7.0/cli/php.ini"
sed -i "s:$SEARCH:$REPLACE:" $FILEPATH

References