El comportamiento de estas funciones se ve afectado por la configuración de php.ini.
Dónde se puede realizar un ajuste de configuración.He aquí una breve explicación de las directivas de configuración.
opcache.enable
boolean Habilita la caché de opcode. Cuando está deshabilitado, el código no es optimizado o almacenado en caché. El ajuste opcache.enable
no puede ser habilitado en tiempo de ejecución enabled at runtime a través de ini_set(), solamente puede ser deshabilitado. Intentar habilitarlo en un script gernerará una advertencia.
opcache.enable_cli
booleanHabilita la caché de opcode para la versión CLI de PHP.
opcache.memory_consumption
integerEL tamaño del almacén de memoria compartida utilizado por OPcache, en megabytes.
opcache.interned_strings_buffer
integerLa cantidad de memoria utilizada para almacenar cadenas, en megabytes. Esta directiva de configuración es ignorada en PHP < 5.3.0.
opcache.max_accelerated_files
integer El número máximo de claves (y por lo tanto, de scripts) en la tabla de hash de OPcache. El valor que realmente se utilizará será el primer número en el conjunto de los números primos { 223, 463, 983, 1979, 3907, 7963, 16229, 32531, 65407, 130987 }
que sea mayor o igual al valor configurado. El valor mínimo es 200. El valor máximo es 100000 en PHP < 5.5.6, y 1000000 en versiones posteriores.
opcache.max_wasted_percentage
integerEl porcentaje máximo de memoria desperdiciada que está permitida antes de que un reinicio sea programado.
opcache.use_cwd
booleanSi está habilitada, OPcache añade el directorio de trabajo actual a la clave del script, eliminado así las posibles colisiones entre ficheros con el mismo nombre base. Deshabilitar esta directiva mejora el rendimiento pero podría generar problemas en aplicaciones existentes.
opcache.validate_timestamps
booleanSi está habilitado, OPcache consultará por scripts actualizados cada opcache.revalidate_freq segundos. Cuando esta directiva está deshabilitada, se debe reiniciar OPcache de forma manual mediante opcache_reset(), opcache_invalidate() o reiniciando el servidor web para que los cambios en el sistema de ficheros tomen efecto.
opcache.revalidate_freq
integer La frecuencia de verificación de las marcas temporales de Unix de los scripts por actualizaciones, en segundos. 0
hará que OPcache consulte por actualizaciones en cada petición.
Esta directiva de configuración es ignorada si opcache.validate_timestamps está deshabilitada.
opcache.revalidate_path
booleanSi está deshabilitada, los ficheros cacheados existentes que usen el mismo include_path serán reutilizados. Por lo tanto, si un fichero con el mismo nombre está en algún otro lado del include_path, no será encontrado.
opcache.save_comments
booleanSi está deshabilitada, todos los comentarios de la documentación serán elliminados de la caché de opcode para reducir el tamaño del código optimizado. Deshabilitar esta directiva de configuración podría generar problemas en aplicaciones y frameworks que dependen del análisis de comentarios para anotaciones, incluyendo Doctrine, Zend Framework 2 y PHPUnit.
opcache.load_comments
booleanSi está deshabilitada, los comentarios de la documentación no serán cargados de la caché de opcode aun si éstos existen. Esto puede ser usado junto con opcache.save_comments para cargar sólo los comentarios para las aplicaciones que los requieran.
opcache.fast_shutdown
booleanSi está habilitada, una secuencia de apagado rápida es utilizada que no libera cada bloque asignado sino que depende del gestor de memoria del Zend Engine para rescindir del conjunto de variables de petición completo.
Esta directiva ha sido eliminada en PHP 7.2.0. Se ha integrado una variante de la secuencia de apagado rápido en PHP, y será usada automáticamente si es posible.
opcache.enable_file_override
booleanCuando está habilitada, la caché de opcode será consultado para determinar si un fichero ya ha sido cacheado cuando file_exists(), is_file() y is_readable() son llamadas. Esto puede incrementar el rendimiento en aplicaciones que chequean la existencia y legibilidad de los scripts PHP, pero arriesgando devolver datos obsoletos si opcache.validate_timestamps está deshabilitada.
opcache.optimization_level
integerUn bitmask que controla cúales permisos de optimización son ejecutados.
opcache.inherited_hack
boolEsta directiva de configuración es ignorada.
opcache.dups_fix
booleanEste hack debería estar habilitado para funcionar sólo para evitar errores "Cannot redeclare class".
opcache.blacklist_filename
stringLa ubicación del fichero de blacklist de OPcache. Un fichero blacklist es un texto que contiene los nombres de los ficheros que no deberían ser acelerados, uno por línea. Se permiten comodines, y prefijos también pueden ser provistos. Las líneas que comienzen con un punto y coma son ignoradas como comentarios.
Un fichero blacklist simple luciría así:
; Matches a specific file. /var/www/broken.php ; A prefix that matches all files starting with x. /var/www/x ; A wildcard match. /var/www/*-broken.php
opcache.max_file_size
integer El tamaño de fichero máximo que será almacenado en caché, en bytes. Si es 0
, todos los ficheros serán almacenados en caché.
opcache.consistency_checks
integerSi es distinto de cero, OPcache verificará el checksum de la caché cada N peticiones, donde N es el valor de esta directiva de configuración. Esto debería sólo estar habilitado durante la depuración ya que puede tener un impacto negativo en el rendimiento.
opcache.force_restart_timeout
integerLa cantidad de tiempo a esperar el comienzo de un reinicio programado si la caché no está activa, en segundos. Si se acaba el tiempo, entonces OPcache asume que algo anda mal y terminará todos los procesos que bloqueen la caché para permitir un reinicio.
Si opcache.log_verbosity_level es 2 o más, una advertencia será guardada en el registro de errores si esto ocurre.
opcache.error_log
string El registro de errores de errores de OPcache. Una cadena vacía es tratada de igual forma que stderr
, y resultará en registros siendo enviados a errores estándar (que será el registro de errores del servidor Web en la mayoría de los casos).
opcache.log_verbosity_level
integerEl nivel de verbosidad del registro. Por defecto, sólo los errores fatales (nivel 0) y errores (nivel 1) son registrados. Otros niveles disponibles son advertencias (nivel 2), mensajes de información (nivel 3) y mensajes de depuración (nivel 4).
opcache.record_warnings
boolIf enabled, OPcache will record compile-time warnings and replay them on the next include, even if it is served from cache.
opcache.preferred_memory_model
stringEl modelo de memoria principal que utilizará OPcache. Si se deja vacío, OPcache seleccionará el modelo más apropiado, el cual es el comportamiento correcto en prácticamente todos los casos.
Los valores posibles incluyen mmap
, shm
, posix
y win32
.
opcache.protect_memory
booleanProtege la memoria compartida de escrituras inesperadas mientras se ejecutan scripts. Esto es útil sólo para depuración interna.
opcache.mmap_base
stringLa base usada para los segmentos de memoria compartida en Windows. Todos los procesos PHP deben mapear la memoria compartida con el mismo espacio de direcciones. Utilizando esta directiva se corrigen los errores "Unable to reattach to base address".
opcache.restrict_api
stringPermite llamar a funciones de la API de OPcache solamente desde scripts de PHP cuya ruta comience con la cadena especificada. El valor predeterminado de "" significa sin restricciones.
opcache.file_update_protection
stringPreviene de almacenar en caché ficheros que estén menos que este número de segundos. Protege del almacenamiento en caché de ficheros no actualizados completamente. En caso de que todas las actualizaciones de ficheros del sitio sean atómicas, se puede aumentar el rendimiento estableciéndolo a "0".
opcache.huge_code_pages
stringHabilita o inhabilita la copia de código de PHP (segmento de texto) a HUGE PAGES. Esto debería mejorar el rendimiento, aunque requiere una configuración apropiada del SO.
opcache.lockfile_path
stringRuta absoluta usada para almacenar shared lockfiles compartidos (solo para *nix)
opcache.opt_debug_level
stringProduce volcados de opcode para depurar diferentes escenarios de optimización. 0x10000 generará opcodes a medida que el compilador los haya producido antes de ocurra cualquier optimización, mientras que 0x20000 generará códigos optimizados.
opcache.file_cache
stringHabilita y establece el segundo nivel de directorio de caché. Debería mejorar el rendimiento cuando la memoria SHM esté llena, cuando se reinicie el servidor o se restablezca la SHM. El valor predeterminado "" inhabilita el almacenamiento en cache basado en ficheros.
opcache.file_cache_only
booleanHabilita o inhabilita el almacenamiento de opcodes en memoria compartida.
opcache.file_cache_consistency_checks
booleanHabilita o inhabilita la validación del checksum cuando un script sea cargado desde la caché de ficheros.
opcache.file_cache_fallback
booleanImplica opcache.file_cache_only=1 para ciertos procesos que fallan al volver a vincularse a la memoria conpartida (solo Windows). Es necesaria la caché de ficheros explícitamente.
La inhabilitación de esta opción de configuración puede evitar el inicio de procesos, por lo que está desaconsejado.
opcache.validate_permission
booleanValida los permisos de ficheros almacenados en caché con el usuario en uso.
opcache.validate_root
booleanEvita la colisión de nombres en entornos con chroot. Debe estar habilitado en todos los entornos con chroot para evitar el acceso a ficheros fuera de chroot.
opcache.preload
stringEspecifica un script de PHP que va a ser compilado y ejecutado en el arranque del servidor, lo que podría precargar otros ficheros, ya sea con include o usando la función opcache_compile_file(). Todas las entidades (p. ej. funciones y clases) definidas en estos ficheros estarán disponibles para peticiones listas para usar, hasta que el servidor sea apagado.
opcache.preload_user
stringLa precarga de código como «root» no está permitida por razones de seguridad. Esta directiva facilita que la precarga se ejecute como otro usuario.
opcache.cache_id
stringOn Windows, all processes running the same PHPSAPI under the same user account having the same cache ID share a single OPcache instance. The value of the cache ID can be freely chosen.
For IIS, different application pools can have their own OPcache instance by using the environment variable APP_POOL_ID as opcache.cache_id
.
opcache.jit
string|intFor typical usage, this option accepts one of four string values:
disable
: Completely disabled, cannot be enabled at runtime.off
: Disabled, but can be enabled at runtime.tracing
/on
: Use tracing JIT. Enabled by default and recommended for most users. function
: Use function JIT. For advanced usage, this option accepts a 4-digit integer CRTO
, where the digits mean:
C
(CPU-specific optimization flags)0
: Disable CPU-specific optimization.1
: Enable use of AVX, if the CPU supports it.R
(register allocation)0
: Don't perform register allocation.1
: Perform block-local register allocation.2
: Perform global register allocation.T
(trigger)0
: Compile all functions on script load.1
: Compile functions on first execution.2
: Profile functions on first request and compile the hottest functions afterwards. 3
: Profile on the fly and compile hot functions.4
: Currently unused.5
: Use tracing JIT. Profile on the fly and compile traces for hot code segments. O
(optimization level)0
: No JIT.1
: Minimal JIT (call standard VM handlers).2
: Inline VM handlers.3
: Use type inference.4
: Use call graph.5
: Optimize whole script."tracing"
mode corresponds to CRTO = 1254
, the "function"
mode corresponds to CRTO = 1205
. opcache.jit_buffer_size
intThe amount of shared memory to reserve for compiled JIT code. A zero value disables the JIT.
Cuando se usa un integer, el valor del mismo es medido en bytes. También se puede usar la notación reducida, tal como se describe en esta FAQ.opcache.jit_debug
intA bit mask specifying which JIT debug output to enable. For possible values, please consult zend_jit.h.
opcache.jit_bisect_limit
int Debugging option that disables JIT compilation after compiling a certain number of functions. This may be helpful to bisect the source of a JIT miscompilation. Note: this option only works when JIT trigger is set to 0 (compile on script load) or 1 (compile on first execution), e.g., opcache.jit=1215
. See more in opcache.jit option.
opcache.jit_prof_threshold
floatWhen using the "profile on first request" trigger mode, this threshold determines whether a function is considered hot. The number of calls to the function divided by the number of calls to all functions must be above the threshold. For example, a threshold of 0.005 means that functions that made up more than 0.5% of all calls will be JIT compiled.
opcache.jit_max_root_traces
intMaximum number of root traces. The root trace is an execution flow taking one path through the code firstly, which is a unit of JIT compilation. JIT will not compile new code if it reaches this limit.
opcache.jit_max_side_traces
intMaximum number of side traces a root trace may have. The side trace is another execution flow that does not follow the path of compiled root trace. Side traces belonging to the same root trace will not be compiled if it reaches this limit.
opcache.jit_max_exit_counters
intMaximum number of side trace exit counters. This limits the total number of side traces there may be, across all root traces.
opcache.jit_hot_loop
int After how many iterations a loop is considered hot. Valid value range is [0,255]
; for any setting out of this range, e.g., -1 or 256, default value will be used instead. Specially, a zero value will disable JIT to trace and compile any loops.
opcache.jit_hot_func
int After how many calls a function is considered hot. Valid value range is [0,255]
; for any setting out of this range, e.g., -1 or 256, default value will be used instead. Specially, a zero value will disable JIT to trace and compile any functions.
opcache.jit_hot_return
int After how many returns a return is considered hot. Valid value range is [0,255]
; for any setting out of this range, e.g., -1 or 256, default value will be used instead. Specially, a zero value will disable JIT to trace and compile any returns.
opcache.jit_hot_side_exit
int After how many exits a side exit is considered hot. Valid value range is [0,255]
; for any setting out of this range, e.g., -1 or 256, default value will be used instead. Specially, a zero value will disable JIT to trace and compile any side exits.
opcache.jit_blacklist_root_trace
intMaximum number of times the compilation of a root trace is attempted before it is blacklisted.
opcache.jit_blacklist_side_trace
intMaximum number of times the compilation of a side trace is attempted before it is blacklisted.
opcache.jit_max_loop_unrolls
intMaximum number of attempts to unroll a loop in a side trace, trying to reach the root trace and close the outer loop.
opcache.jit_max_recursive_calls
intMaximum number of unrolled recursive call loops.
opcache.jit_max_recursive_returns
intMaximum number of unrolled recursive return loops.
opcache.jit_max_polymorphic_calls
intMaximum number of attempts to inline polymorphic (dynamic or method) calls. Calls above this limit are treated as megamorphic and are not inlined.