您的位置:首页 > 编程语言 > PHP开发

php Zend Opcache,xcache,eAccelerator缓存优化详解(具体根据个人需要选择其一即可,功能都一样切勿重复选择)

2013-08-05 18:36 651 查看
XCACHE
XCache 是一个开源的 opcode 缓存器/优化器, 这意味着他能够提高您服务器上的 PHP 性能. 他通过把编译 PHP 后的数据缓冲到共享内存从而避免重复的编译过程, 能够直接使用缓冲区已编译的代码从而提高速度. 通常能够提高您的页面生成速率 2 到5 倍, 降低服务器负载. XCache 是一个又快又稳定的 PHP opcode 缓存器. 经过良好的测试并在大流量/高负载的生产机器上稳定运行. 经过(在 linux 上)测试并支持所有现行 PHP 分支的最新发布版本, 如 PHP_4_3 PHP_4_4 PHP_5_0 PHP_5_1 PHP_5_2 HEAD(6.x), 并支持线程安全/Windows. 与同类 opcode 缓存器相比更胜一筹, 比如能够快速跟进 PHP 版本.XCache 工程由 mOo 领队, 他也是 Lighttpd 的开发成员之一. Lighttpd 是最快的 Web 服务器应用程序之一, 并且超越 Apache 以及许多其他 Web 服务器. XCache 努力达到类似的效果. XCache 的INI配置详解 载入 XCache 模块

引用
;; 安装成 zend extension (推荐), 路径一般是 "$extension_dir/xcache.so"
zend_extension = /usr/local/lib/php/extensions/non-debug-non-zts-xxx/xcache.so
;; Windows 系统例子:
zend_extension_ts = c:/php/extensions/php_xcache.dll
;; 或者您也可把 XCache 安装成 extension, 注意确保您的 extension_dir 设置正确, 并
把 xcache.so 或者 php_xcache.dll 放到该目录里面
; extension = xcache.so
;; 或者 Win32 系统:
; extension = php_xcache.dll

XCache Administration

xcache.admin.user string
验证名.
xcache.admin.pass string
md5 后的验证密码, 亦即 md5(您的密码), 留空则禁用管理页面.
xcache.test string
仅在测试一些功能的时候才启用. 如果您不知道这个功能的作用, 则您不需要知道.
xcache.coredump_directory string
设置在 crash (SIGSEGV/SIGABRT) 时保存 core dump 文件的路径. 留空则禁止, 或者设置为类似 "/tmp/phpcore/" 的目录. 确保这个路径可以被 php 写入文件. (与 open_basedir 无关).
xcache.admin.enable_auth string
如果你打算自己处理验证, 用这个选项禁止 HTTP 验证功能. 值得注意的是任意 vhost 用户都可以安装一个 XCache admin 页面, 如果禁止了内建 HTTP 验证, 则他们亦不需要权限即可访问管理页面. 出于安全考虑, 您应该尽量考虑保留 XCache 内建验证功能, 针对 XCache admin 页面特定地址取消网页服务器的 mod_auth 这个选项仅在 1.2.x 系列有作用, 起始版本 1.2.1

XCache Cacher

xcache.cacher boolean
使用/不使用 opcode 缓存器. xcache.size = 0 时无效.
xcache.size int
0 禁止, 非 0 则启用缓存器. 请注意您系统所允许的 mmap 最大值.
xcache.count int
指定将 cache 切分成多少块. 参考 SplittedCache
xcache.slots size
只是作为 hash 槽个数的参考值, 您可以放心地缓冲超过这个个数的项目.
xcache.ttl seconds
设置缓冲项目的 Ttl (Time To Live) 值, 0=永不过期.
xcache.gc_interval seconds
检查过期项目, 回收内存空间的间隔.
xcache.var_size int
xcache.var_count int
xcache.var_slots size
xcache.var_gc_interval seconds
同上, 不过用于数据缓冲而不是 opcode 缓冲.
xcache.var_ttl seconds
xcache_(get|set|inc|dec) 等的默认 ttl 值.
xcache.var_maxttl seconds
最大 ttl 值, 程序无法指定超过这个最大值的 ttl.
xcache.readonly_protection boolean
如果启用了 ReadonlyProtection, 将会略微降低性能, 但是会提高一定的安全系数. 这个选项对于 xcache.mmap_path = /dev/zero 无效.
xcache.mmap_path string
对于 *nix, xcache.mmap_path 是 文件路径, 不是目录. 对于 Win32, xcache.mmap_path 只是匿名的 map 名, 不是实际的文件路径. 如果您要启用 ReadonlyProtection 请用类似 "/tmp/xcache" 的路径. 2 组 php 不该共用同一个路径 (/dev/zero 除外).

XCache Optimizer

xcache.optimizer boolean
启用优化器 (目前无效).

XCache Coverager

xcache.coverager boolean
Enable coverage data collecting for xcache.coveragedump_directory and xcache_coverager_start/stop/get/clean() functions (will hurt executing performance)
xcache.coveragedump_directory string
Directory to dump coverage data. Make sure it's readable (care open_basedir) by coverage viewer script. Requires xcache.coverager=On eAccelerator
1、背景
eAccelerator 是一个免费开源的PHP加速、优化、编译和动态缓存的项目,它可以通过缓存PHP代码编译后的结果来提高PHP脚本的性能,使得一向很复杂和离我们很远的PHP脚本编译问题完全得到解决。通过使用eAccelerator,可以优化你的PHP代码执行速度,降低服务器负载,可以提高PHP应用执行速度最高达10倍。
eAccelerator 项目诞生于2004年,当时它是作为 Turck MMCache 项目的一个分支提出并投入开发的。 Turck MMCache 由 Dmitry Stogov 开发,是个非常优秀的PHP内存缓存加速系统,如今仍然有很大部分 eAccelerator 的代码应用到该项目中,目前该项目有很长时间没有更新了,对于最新的PHP版本支持还未推出。
2、原理
eAccelerator 通过把经过编译后的PHP代码缓存到共享内存中,并在用户访问的时候直接调用从而起到高效的加速作用。它的效率非常高,从创建共享内存到查找编译后的代码都在非常短的时间内完成,对于不能缓存到共享内存中的文件和代码,eAccelerator还可以把他们缓存到系统磁盘上。
eAccelerator 同样还支持PHP代码的编译和解释执行,你可以通过encoder.php脚本来对php代码进行编译达到保护代码的目的,经过编译后的代码必须运行在安装了eAccelerator的环境下。eAccelerator编译后的代码不能被反编译,它不象其他一些编译工具那样可以进行反编译,这将使得代码更加安全和高效。
最新的PHP5.4.8安装eAccelerator,
需要注意的是要安装高版本的,低了编译不过去。
官网:http://eaccelerator.net/

1.下载安装eAccelerator
#wget https://github.com/eaccelerator/eaccelerator/tarball/master
最新的版本是eaccelerator-42067ac.tar.gz
#tar zxvf eaccelerator-42067ac.tar.gz
需要phpize安装php扩展,如果不明白phpize可以看这个:/article/2648039.html
需要注意的是需要写php的安装路径对应的phpize下面的php-config也是
# /usr/local/webserver/php/bin/phpize
需要记住生成的提示信息下面配置php要用到
/usr/local/webserver/php/lib/php/extensions/no-debug-non-zts-
20100525/



#./configure --enable-eaccelerator=shared --with-php-config=/usr/local/webserver/php/bin/php-config
# make
需要注意的是要安装高版本的,低了编译不过去。
# make install

2.配置php.ini配置文件
[eaccelerator]
extension="/data/webserver/php/lib/php/extensions/no-debug-zts-20060613/eaccelerator.so"
eaccelerator.shm_size="32"
eaccelerator.cache_dir="/data/cache/eaccelerator"
eaccelerator.enable="1"
eaccelerator.optimizer="1" (如果没有安装optimizer请设置为0关闭加速引擎,否则会出现PHP脚本错误)
eaccelerator.check_mtime="1"
eaccelerator.debug="0"
eaccelerator.filter=""
eaccelerator.shm_max="0"
eaccelerator.shm_ttl="0"
eaccelerator.shm_prune_period="0"
eaccelerator.shm_only="0"
eaccelerator.compress="1"
eaccelerator.compress_level="9"
  
建立缓存目录:
# mkdir -p /data/cache/eaccelerator
# chmod 0777 /data/cache/eaccelerator
  
重启Apache:
# service httpd restart
3、检查ZendOptimizer和eaccelerator是否安装成功
  
创建一个phpinfo.php文件,内容如下:
  <?php
   phpinfo();
  ?>
  
  将该文件放置到网站目录,在浏览器中访问,如果出现以下内容则安装成功:
  This program makes use of the Zend Scripting Language Engine:
  Zend Engine v2.2.0, Copyright (c) 1998-2007 Zend Technologies
   with eAccelerator v0.9.5, Copyright (c) 2004-2006 eAccelerator, by eAccelerator
   with Zend Extension Manager v1.0.11, Copyright (c) 2003-2006, by Zend Technologies
   with Zend Optimizer v3.2.2, Copyright (c) 1998-2006, by Zend Technologies
  
  
  
  二、eaccelerator配置信息详解(根据官方英文说明翻译)
  
  extension="/data/webserver/php/lib/php/extensions/no-debug-zts-20060613/eaccelerator.so"
  
  解释:PHP扩展eaccelerator.so的路径。
  
  --------------------
  
  eaccelerator.shm_size="32"
  
  解释:eaccelerator可使用的共享内存大小(单位为MB)。
  
  在Linux下,单个进程的最大内存使用量受/proc/sys/kernel/shmmax中设置的数字限制(单位为字节),例如CentOS 4.4的shmmax默认值为33554432字节(33554432bytes/1024/1024=32MB)。
  
  临时更改该值:
  # echo 字节数 > /proc/sys/kernel/shmmax
  
  按照以上方法更改,在每次重启系统时,该值会被自动还原。如果想永久更改,可以修改/etc/sysctl.conf文件,设置:
  kernel.shmmax = 字节数
  
  --------------------
  
  eaccelerator.cache_dir="/data/cache/eaccelerator"
  
  解释:缓存路径,可以使用命令mkdir -p /data/cache/eaccelerator创建该目录,然后使用命令chmod 0777 /data/cache/eaccelerator设置该目录权限为0777
  
  --------------------
  
  eaccelerator.enable="1"
  
  解释:打开或者关闭eaccelerator。"1"指打开,"0"指关闭。默认值为"1"。
  
  --------------------
  
  eaccelerator.optimizer="1" (如果没有安装optimizer请设置为0关闭加速引擎,否则会出现PHP脚本错误)

  解释:打开或者关闭代码优化,开启可以加快代码的执行速度。"1"指打开,"0"指关闭。默认值为"1"。
  
  --------------------
  
  eaccelerator.check_mtime="1"
  
  解释:当打开此项时,eaccelerator会在每次请求时检查php文件的修改时间,看其是否被修改过,这会耗费一点时间,如果php文件被修改过,eaccelerator会重新编译缓存该php文件。当关闭此项时,如果php文件被修改,则需要手工删除eaccelerator缓存,才能显示被修改的php文件。"1"指打开,"0"指关闭。默认值为"1"。
  
  --------------------
  
  eaccelerator.debug="0"
  
  解释:打开或者关闭调试记录。当打开时,eaccelerator会将对一个缓存文件的每次请求都写进log。打开此项只对调试eaccelerator是否有BUG时有益处。"1"指打开,"0"指关闭。默认值为"0"。
  
  --------------------
  
  eaccelerator.filter=""
  
  解释:决定哪些PHP文件应该被缓存。可以指定一个范围(比如"*.php *.phtml"),这样被指定的文件就会被缓存。如果该范围以!开头,被指定的文件就不会被缓存。默认值为"",表示缓存所有的PHP文件。
  
  --------------------
  
  eaccelerator.shm_max="0"
  
  解释:一个用户使用例如eaccelerator_put之类的函数能够往共享内存中加载的最大数据。默认值为"0",表示不限制。(单位为字节)
  
  --------------------
  
  eaccelerator.shm_ttl="0"
  
  解释:当没有足够的空闲共享内存去尝试缓冲一个新脚本时,将删除至少在shm_ttl秒之前没有被访问过的文件。默认值为"0",表示不尝试从共享内存中删除任何旧的脚本。(单位为秒)
  
  --------------------
  
  eaccelerator.shm_prune_period="0"
  
  解释:当没有足够的空闲共享内存去尝试缓冲一个新脚本时,将删所有旧脚本,前提是这个尝试在超过shm_prune_period秒之前被执行过。默认值为"0",表示不尝试从共享内存中删除任何旧的脚本。(单位为秒)
  
  --------------------
  
  eaccelerator.shm_only="0"
  
  解释:打开或者关闭在磁盘上缓存编译过的脚本。这个参数对会话数据和内容缓存没有效果。默认值为"0",表示使用磁盘和共享内存来缓存。
  
  --------------------
  
  eaccelerator.compress="1"
  
  解释:打开或者关闭缓存内容压缩。"1"指打开,"0"指关闭。默认值为"1"。
  
  --------------------
  
  eaccelerator.compress_level="9"
  
  解释:内存压缩的级别。默认值为"9",表示最大压缩。


#这个是我机器的so位置
extension="/usr/local/webserver/php/lib/php/extensions/no-debug-non-zts-20100525/eaccelerator.so"
#这个是设置一个缓存大小
eaccelerator.shm_size="64"
#缓存目录
eaccelerator.cache_dir="/usr/local/webserver/eaccelerator_cache" 实际配置不建议放在WEB目录下,考虑到安全因素建议放到web目录以外
#网站目录,把解开的eAccelerator 的源码包里的control.php 文件复制到你的WEB 服务器中的一个目录下,使其它以通过http 访问,如果不加那么看不到缓存的页面列表,但是还是可以看到内存信息
eaccelerator.allowed_admin_path=/usr/www/
eaccelerator.enable="1"
eaccelerator.optimizer="1" (如果没有安装optimizer请设置为0关闭加速引擎,否则会出现PHP脚本错误)
eaccelerator.check_mtime="1"
eaccelerator.debug="0"
eaccelerator.filter=""
eaccelerator.shm_max="0"
eaccelerator.shm_ttl="0"
eaccelerator.shm_prune_period="0"
eaccelerator.shm_only="0"
eaccelerator.compress="1"
eaccelerator.compress_level="9"
eaccelerator.keys = "disk_only"
eaccelerator.sessions = "disk_only"
eaccelerator.content = "disk_only"
设置内容缓存的存放的地方,可以设置为:
shm_and_disk 在共享缓存和硬盘(默认值)
shm 默认存在共享内存,如果共享内存已满或大小超过 "eaccelerator.shm_max" 的值,就存到硬盘
shm_only 只存放在共享内存
disk_only 只存放在硬盘
none 不缓存数据
这里为了查看效果设置为存在硬盘

增加权限
#mkdir /usr/local/webserver/eaccelerator_cache
#chmod 777 /usr/local/webserver/eaccelerator_cache

3.测试查看phpinfo()






4.查看缓存文件夹
为了直观所以截图图形界面



这说明成功生成了缓存

5.更好的监控方式
eAccelerator控制面板的地址,安装包里有一个control.php文件,把它复制到网站的任意目录,可以用它查看和管理,这个必须指定,否则查看缓存内容的时候会出错,访问时候默认的用户名是:admin,密码:eAccelerator




注意,之前的php.ini配置文件加上这个配置就会看到明细信息
eaccelerator.allowed_admin_path=/usr/www/




重启apache则会清空缓存

文档:
eaccelerator.shm_size="8"
eAccelerator 可以使用的共享内存的数量 (以MB为单位) . "0" 是指操作系统的默认值,默认值是 "0",可根据服务器的实际情况来调整:16、32、64、128都是可以的。
eaccelerator.cache_dir="/usr/local/webserver/eaccelerator_cache"
这个目录是给磁盘缓存使用,eAccelerator 在这里储存预先编译好的代码,进程数据,内容以及用户的自定义内容。同样的数据也能被储存在共享内存中 (这样可以提高访问速度)
eaccelerator.enable="1"
开启或关闭 eAccelerator,"1" 为开启,"0" 为关闭。默认值为 "1"。
eaccelerator.optimizer="1" (如果没有安装optimizer请设置为0关闭加速引擎,否则会出现PHP脚本错误)
启或关闭内部优化器,可以提升代码执行速度。"1" 为开启,"0" 为关闭。默认值为 "1"。
eaccelerator.check_mtime="1"
打开或者关闭 PHP 的文件修改检查,"1" 是指打开,"0" 是指关闭。默认值是 "1"。
eaccelerator.debug="0"
开启或关闭调试日志记录。"1" 为开启,"0" 为关闭。默认值为 "0"。会将缓存命中得记录写入日志。
eaccelerator.filter=""
判断哪些 PHP 文件必须缓存。可以指定缓存和不缓存的文件类型(如 "*.php *.phtml"等)如果参数以 "!" 开头,则匹配这些参数的文件被忽略缓存。默认值为 "",即,所有 PHP 文件都将被缓存。
eaccelerator.shm_max="0"
当使用 " eaccelerator_put() " 函数时禁止其向共享内存中存储过大的文件。该参数指定允许存储的最大值,单位:字节 (10240, 10K, 1M)。"0" 为不限制。默认值为 "0"。
eaccelerator.shm_ttl="3600"
当 eAccelerator 获取新脚本的共享内存大小失败时,它将从共享内存中删除所有在最后 "shm_ttl" 秒内没有存取的脚本缓存。默认值为"0",为不从共享内存中删除任何缓存文件。
eaccelerator.shm_prune_period="3600"
当 eAccelerator 获取新脚本的共享内存大小失败时,他将试图从共享内存中删除早于"shm_prune_period" 秒的缓存脚本。默认值为 "0",为不从共享内存中删除任何缓存文件。
eaccelerator.shm_only="0"
允许或禁止将已编译脚本缓存在磁盘上。该选项对 session 数据和内容缓存无效。默认值为 "0",为使用磁盘和共享内存进行缓存。
eaccelerator.compress="1"
允许或禁止压缩内容缓存。默认值为 "1",为允许压缩。
eaccelerator.compress_level="9"
指定内容缓存的压缩等级。默认值为 "9",为最高等级。
eaccelerator.keys = "disk_only"
eaccelerator.sessions = "disk_only"
eaccelerator.content = "disk_only"
设置内容缓存的存放的地方,可以设置为:
shm_and_disk 在共享缓存和硬盘(默认值)
shm 默认存在共享内存,如果共享内存已满或大小超过 "eaccelerator.shm_max" 的值,就存到硬盘
shm_only 只存放在共享内存
disk_only 只存放在硬盘
none 不缓存数据

6.测试性能
快速排序代码
[php] view plaincopyprint?<?php
function quickSort($arr)
{
$len = count($arr);
if($len <= 1) {
return $arr;
}
$key = $arr[0];
$left_arr = array();
$right_arr = array();

for($i=1; $i<$len; $i++){
if($arr[$i] <= $key){
$left_arr[] = $arr[$i];
} else {
$right_arr[] = $arr[$i];
}
}

$left_arr = quickSort($left_arr);
$right_arr = quickSort($right_arr);
return array_merge($left_arr, array($key), $right_arr);
}


$arr = array(6,3,8,5,9,2,10);
echo '<pre>';
print_r(quickSort($arr));
?>
[php] view plaincopyprint?<?php
function quickSort($arr)
{
$len = count($arr);
if($len <= 1) {
return $arr;
}
$key = $arr[0];
$left_arr = array();
$right_arr = array();

for($i=1; $i<$len; $i++){
if($arr[$i] <= $key){
$left_arr[] = $arr[$i];
} else {
$right_arr[] = $arr[$i];
}
}

$left_arr = quickSort($left_arr);
$right_arr = quickSort($right_arr);
return array_merge($left_arr, array($key), $right_arr);
}


$arr = array(6,3,8,5,9,2,10);
echo '<pre>';
print_r(quickSort($arr));
?>
<?php
       function quickSort($arr)
       {
           $len    = count($arr);
           if($len <= 1) {
               return $arr;
           }
           $key = $arr[0];
           $left_arr    = array();
           $right_arr    = array();

           for($i=1; $i<$len; $i++){
               if($arr[$i] <= $key){
                   $left_arr[] = $arr[$i];
               } else {
                   $right_arr[] = $arr[$i];
               }
           }

           $left_arr    = quickSort($left_arr);
           $right_arr    = quickSort($right_arr);
           return array_merge($left_arr, array($key), $right_arr);
       }

       $arr = array(6,3,8,5,9,2,10);
       echo '<pre>';
       print_r(quickSort($arr));
       ?>


测试方法

#ab -n 1000 http://192.168.2.107/quicksort.php
连续测试几次,主要的性能指标是Requests per second

左边是没有使用eAccelerator 时的情况,右边是使用了的



连续测试10次,基本数据还是比较稳定的。
使用了eAccelerator 时比没使用的要好!

使用strace查看C语言级别的php源码

可以看eAccelerator缓存是怎么被读取的完成过程

扩展阅读:
eAccelerator提供如下的API接口和文件:(下述文件均在源码包的doc/php/目录下)
文件列表:
cache.php
dasm.php
encoder.php
info.php
loader.php
session.php
shared_memory.php
接口列表:
array eaccelerator_cached_scripts ()
void eaccelerator_cache_output (string $key, string $eval_code, [int $ttl = 0])
void eaccelerator_cache_page (string $key, [int $ttl = 0])
void eaccelerator_cache_result (string $key, string $code, [int $ttl = 0])
void eaccelerator_caching (boolean $flag)
void eaccelerator_clean ()
void eaccelerator_clear ()
array eaccelerator_dasm_file (mixed $filename)
mixed eaccelerator_encode (mixed $src, [mixed $prefix = ''], [string $pre_content = ''], [string $post_content = ''])
void eaccelerator_gc ()
mixed eaccelerator_get (string $key)
array eaccelerator_info ()
array eaccelerator_list_keys ()
void eaccelerator_load ()
boolean eaccelerator_lock (string $key)
void eaccelerator_optimizer (boolean $flag)
void eaccelerator_purge ()
boolean eaccelerator_put (string $key, mixed $value, [int $ttl = 0])
array eaccelerator_removed_scripts ()
boolean eaccelerator_rm (string $key)
void eaccelerator_rm_page (string $key)
boolean eaccelerator_set_session_handlers ()
boolean eaccelerator_unlock (string $key)
有关上述文档详细说明请参考官方文档

下面有部分网友翻译后的接口说明:
eaccelerator_put($key, $value, $ttl=0)
将 $value 以 $key 为键名存进缓存(php4下支持对像类型,看源码好像zend2里不支持了),$ttl 是这个缓存的生命周期,单位是秒,省略该参数或指定为 0 表示不限时,直到服务器重启清空为止。

eaccelerator_get($key)
根据 $key 从缓存中返回相应的 eaccelerator_put() 存进去的数据,如果这项缓存已经过期或不存在那么返回值是 NULL

eaccelerator_rm($key)
根据 $key 移除缓存

eaccelerator_gc()
移除清理所有已过期的 key

eaccelerator_lock($key)
为 $key 加上锁定操作,以保证多进程多线程操作时数据的同步。需要调用 eaccelerator_unlock($key) 来释放这个锁或等待程序请求结束时自动释放这个锁。
例如:
<?php
eaccelerator_lock(“count”);
eaccelerator_put(“count”,eaccelerator_get(“count”)+1));
?>

eaccelerator_unlock($key)
根据 $key 释放锁

eaccelerator_cache_output($key, $eval_code, $ttl=0)
将 $eval_code 代码的输出缓存 $ttl 秒,($ttl参数同 eacclerator_put)
例如:
<?php eaccelerator_cache_output(‘test’, ‘echo time(); phpinfo();’, 30); ?>

eaccelerator_cache_result($key, $eval_code, $ttl=0)
将 $eval_code 代码的执行结果缓存 $ttl 秒,($ttl参数同 eacclerator_put),类似 cache_output
例如:
<?php eaccelerator_cache_result(‘test’, ‘ time() . “Hello”;’, 30); ?>

eaccelerator_cache_page($key, $ttl=0)
将当前整页缓存 $ttl 秒。
例如:
<?php
eaccelerator_cache_page($_SERVER['PHP_SELF'].’?GET=’.serialize($_GET),30);
echo time();
phpinfo();
?>

eaccelerator_rm_page($key)
删除由 eaccelerator_cache_page() 执行的缓存,参数也是 $key

2、PHP代码中使用eAccelerator加速

另外,在PHPCMS里面已经集成了对eAccelerator的支持,下面是一段来自PHPCMS里面的代码
class cache
{
    function __construct()
    {
    }

    function cache()
    {
		$this->__construct();
    }

    function get($name)
    {
        return eaccelerator_get($name);
    }

    function set($name, $value, $ttl = 0)
    {
        eaccelerator_lock($name);
        return eaccelerator_put($name, $value, $ttl);
    }

    function rm($name)
    {
        return eaccelerator_rm($name);
    }

    function clear()
    {
        return eaccelerator_gc();
    }
}


新一代 PHP 加速插件 Zend Opcache

大家知道目前PHP的缓存插件一般有三个:APCeAcceleratorXCache,但未来它们可能都会消失,因为PHP 5.5已经集成Zend Opcache,功能和前三者相似但又有少许不同,缓存速度据说比它们更快(注意:只是据说,我没测试过)。

这几个PHP加速插件的主要原理都相同,就是把PHP执行后的数据缓冲到内存中从而避免重复的编译过程,能够直接使用缓冲区已编译的代码从而提高速度,降低服务器负载,它们的效率是显而易见的,像drupal这种庞大的CMS,每次打开一个页面要调用数十个PHP文件,执行数万行代码,效率可想而知,在安装APC等加速器后打开页面的速度明显加快。

Zend Opcache 已经集成在了PHP 5.5里面,编译安装PHP5.5的时候加上--enable-opcache就行了。但也支持低版本的 PHP 5.2.*, 5.3.*, 5.4.*,未来会取消对5.2的支持,下面是我在PHP 5.4下的安装方法:

依次执行下面的命令
wget http://pecl.php.net/get/zendopcache-7.0.2.tgz tar xzf zendopcache-7.0.2.tgz
cd zendopcache-7.0.2
/usr/local/php/bin/phpize (此处根据实际php安装路径)
./configure --with-php-config=/usr/local/php/bin/php-config
make
make install

如果显示Installing shared extensions: /usr/local/php/lib/php/extensions/no-debug-zts-20100525/ 表示安装完成,下面要修改php的配置文件让它生效

接着呢,配置下php.ini,在最后加上:
[opcache]
zend_extension=opcache.so
opcache.memory_consumption=128
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=4000
opcache.revalidate_freq=60
opcache.fast_shutdown=1
opcache.enable_cli=1
opcache.enable=1一般来说,按照以往的经验,如果加在ZendGuardLoader之前会稳定多了。


128意思是给它分配128M内存,然后重启apache,用phpinfo查看是否生效,显示下面的信息就说明生效了



在phpinfo页面的下面可以看到的运行状态



如果嫌这个不直观可以装个PHP文件查看,地址在https://gist.github.com/ck-on/4959032,把上面的代码保存为一个php文件放到你的网站目录下面打开就可以看到:



命中率100%。

Zend Opcache因为最近才出来,现在还是测试版,相信在未来几年会越来越流行,现在真没多少人用。目前测试来看还比较稳定,我已经在 vbulletin论坛下运行了几天,不过没看出和APC、xcache有啥区别,只是最近我的APC老让apache崩溃(可能是apache和php版本太新的原因),想换个试试,毕竟Zend Opcache和APC都是php官方的,值得信赖。

zend Opcache配置参数详解
我的最终如下,其余参数默认即可。
opcache.memory_consumption=512
opcache.max_accelerated_files=16229
opcache.revalidate_freq=864000
;如果十天半月不改动 php 代码,上面的值尽可能高,单位是秒。
;如果改了,要么重启 apache,要么去上面那个控制面板里“Recheck”。
opcache.enable_file_override=1
opcache.force_restart_timeout=30

OPcache 配置参数中文版如下...(中文和英文同样让人难懂,两种语言文档都啃过了,基本才会了解...):
opcache.enable(默认值:1)
Zend Optimizer + 的开关, 关闭时代码不再优化.

opcache.memory_consumption(默认值:64)
Zend Optimizer + 共享内存的大小, 总共能够存储多少预编译的 PHP 代码(单位:MB).

opcache.interned_strings_buffer(默认值:4)
Zend Optimizer + 中interned字符串的占内存总量.(单位:MB)

opcache.max_accelerated_files(默认值:2000)
Zend Optimizer + 哈希表中键数量的最大值(一个脚本文件应当是对应一个key的,所以应当就是允许缓存的文件最大数量).
这个值实际上是素数列表{ 223, 463, 983, 1979, 3907, 7963, 16229, 32531, 65407, 130987 }中第一个大于设定值的数字.
值设定范围: 200 – 100000

opcache.max_wasted_percentage(默认值:5)
“浪费”的内存达到此值对应的百分比,就会发起一个重启调度.

opcache.use_cwd(默认值:1)
开启这条指令, Zend Optimizer + 会自动将当前工作目录的名字追加到脚本键上, 以此消除同名文件间的键值命名冲突。
关闭这条指令会提升性能,但是会对已存在的应用造成破坏.

opcache.validate_timestamps(默认值:1)
禁用时, 您必须手动重置Zend Optimizer +或重新启动Web服务器,以使文件系统的更改生效.
检查的频率是由指令 “opcache.revalidate_freq” 控制.

opcache.revalidate_freq(默认值:2)
多久(以秒为单位)检查文件时间戳以改变共享内存的分配.”1″ 表示一秒校验一次, 但是是每个请求一次. “0″ 表示总是在校验.

opcache.revalidate_path(默认值:0)
允许或禁止在 include_path 中进行文件搜索的优化. 如果文件搜索被禁用而且可以在相同的 include_path 中找到这个缓存的文件,
文件搜索就不会再进行下去了. 因此,如果 include_path 其它地方有一个同名文件的话, 那就找不到了.
如果这个优化对您的应用有影响,那么应当允许它搜索. 默认情况下,指令是禁止的,这就意味着,优化是处于激活状态的.

opcache.save_comments(默认值:1)
如果禁用,所有的文档注释都从代码中剔除以此减少优化过的代码的大小.
禁用 “文档注释” 可能会破坏一些现有的应用和框架(例如: Doctrine, ZF2, PHPUnit).

opcache.load_comments(默认值:1)
如果禁用, PHP文档注释将不会从 SHM(共享内存) 中读取. 尽管”文档注释”还是会被存储(save_comments=1),
但是那些无论如何都用不上的注释就不必被应用读取了.

opcache.fast_shutdown(默认值:0)
如果开启, 一个快速关闭队列用以提速代码. 快速关闭队列并不释放每个已分配的块, 而是让 Zend 引擎内存管理器来干这个活.

opcache.enable_file_override(默认值:0)
允许覆盖文件存在(file_exists等)的优化特性。

opcache.optimization_level(默认值:0xffffffff)
一个位掩码,其中每个位允许或禁用相应的缓存通过.

opcache.inherited_hack(默认值:1)
启用此Hack可以暂时性的解决”can’t redeclare class”错误. Zend Optimizer + 存储着 DECLARE_CLASS 操作码使用继承的地方
(这些是唯一可以被PHP执行的操作码,但是也可能因为优化引起的父类找不到而无法执行).
当文件被读取时, Optimizer 会试着通过当前环境绑定被继承的类.
这样做的问题是. DECLARE_CLASS 的操作码可能不被当前脚本所需要, 如果脚本需要操作码至少完成类的定义操作, 那么它就会无法执行.
这指令的默认是禁用的, 这就表示优化是有效的. 该在 php 5.3 以及以上的版中不再被需要, 而且这个设置也不会生效.

opcache.dups_fix(默认值:0)
启用此Hack可以暂时性的解决”can’t redeclare class”错误.

opcache.blacklist_filename(默认值:无)
Zend Optimizer + 黑名单文件的位置.
Zend Optimizer + 黑名单是一个文本文件包含了那些不能被加速的文件名.文件格式为每行一个文件名.
文件名须为一个完整的路径或者紧紧一个文件前缀
(如:/var/www/x 屏蔽了 /var/www 文件和目录中所有以 ‘x’ 开始的文件或者目录). 需要屏蔽的文件通常符合下面三个原因中的一个:
1) 目录包含了自动生成的代码, 如 Smarty 或者 ZFW 的缓存.
2) 执行加速时代码无法很好的运行, 从而耽误了编译时评估.
3) 代码触发了一个 Zend Optimizer + 的 Bug

opcache.max_file_size(默认值:0)
通过文件大小屏除大文件的缓存.默认情况下所有的文件都会被缓存.

opcache.consistency_checks(默认值:0)
每 N 次请求检查一次缓存校验.默认值0表示检查被禁用了.由于计算校验值有损性能,这个指令应当紧紧在开发调试的时候开启.

opcache.force_restart_timeout(默认值:180)
从缓存不被访问后,等待多久后(单位为秒)调度重启.Zend Optimizer + 依托此指令来确定一个进程可能在处理过程中出现问题的情况.
这段时间(等待时间)过后, 假设 Zend Optimizer + 发生了一些问题, 并开始干掉那些仍然持有预防重启锁的进程.
当这些发生时, 如果日志的级别是3级或以上, 一个 “killed locker” 的错误就会被记录到 Apache 的日志中.

opcache.error_log(默认值:无)
Zend Optimizer + 的错误日志文件名.留空表示使用标准错误输出(stderr).

opcache.log_verbosity_level(默认值:1)
将错误信息都导向 Web 服务器日志.默认的只有致命错误(level 0) 或者错误(level 1)才会被记录.
你也可以允许警告(level 2),提示消息(level 3) 或者 调试消息(level 4)被记录下来.

opcache.preferred_memory_model(默认值:无)
内存共享的首选后台.留空则是让系统选择.

opcache.protect_memory(默认值:0)
防止共享内存在脚本执行期间被意外写入, 仅用于内部调试.

opcache.mmap_base(默认值:无)
共享内存段映射基础(仅适用于Windows).所有的PHP进程必须映射到相同的共享内存地址空间.
该指令用于手动修复 “Unable to reattach to base address” 错误.
Zend Opcache之可视化PHP源代码:
因为官方源码下载地址偶尔经常出现无法打开的问题,所以这里直接给出了zend opcache的可视化源代码,直接复制即可!

[php] view plaincopy



<?php
/*
OCP - Opcache Control Panel (aka Zend Optimizer+ Control Panel for PHP)
Author: _ck_ (with contributions by GK, stasilok)
Version: 0.1.6
Free for any kind of use or modification, I am not responsible for anything, please share your improvements


* revision history
0.1.6 2013-04-12 moved meta to footer so graphs can be higher and reduce clutter
0.1.5 2013-04-12 added graphs to visualize cache state, please report any browser/style bugs
0.1.4 2013-04-09 added "recheck" to update files when using large revalidate_freq (or validate_timestamps=Off)
0.1.3 2013-03-30 show host and php version, can bookmark with hashtag ie. #statistics - needs new layout asap
0.1.2 2013-03-25 show optimization levels, number formatting, support for start_time in 7.0.2
0.1.1 2013-03-18 today Zend completely renamed Optimizer+ to OPcache, adjusted OCP to keep working
0.1.0 2013-03-17 added group/sort indicators, replaced "accelerator_" functions with "opcache_"
0.0.6 2013-03-16 transition support as Zend renames product and functions for PHP 5.5 (stasilok)
0.0.5 2013-03-10 added refresh button (GK)
0.0.4 2013-02-18 added file grouping and sorting (click on headers) - code needs cleanup but gets the job done
0.0.2 2013-02-14 first public release


* known problems/limitations:
Unlike APC, the Zend OPcache API
- cannot determine when a file was put into the cache
- cannot change settings on the fly
- cannot protect opcache functions by restricting execution to only specific scripts/paths


* todo:
Extract variables for prefered ordering and better layout instead of just dumping into tables
File list filter


*/


// ini_set('display_errors',1); error_reporting(-1);
if ( count(get_included_files())>1 || php_sapi_name()=='cli' || empty($_SERVER['REMOTE_ADDR']) ) { die; } // weak block against indirect access


$time=time();
define('CACHEPREFIX',function_exists('opcache_reset')?'opcache_':(function_exists('accelerator_reset')?'accelerator_':''));


if ( !empty($_GET['RESET']) ) {
if ( function_exists(CACHEPREFIX.'reset') ) { call_user_func(CACHEPREFIX.'reset'); }
header( 'Location: '.str_replace('?'.$_SERVER['QUERY_STRING'],'',$_SERVER['REQUEST_URI']) );
exit;
}


if ( !empty($_GET['RECHECK']) ) {
if ( function_exists(CACHEPREFIX.'invalidate') ) {
$recheck=trim($_GET['RECHECK']); $files=call_user_func(CACHEPREFIX.'get_status');
if (!empty($files['scripts'])) {
foreach ($files['scripts'] as $file=>$value) {
if ( $recheck==='1' || strpos($file,$recheck)===0 ) call_user_func(CACHEPREFIX.'invalidate',$file);
}
}
header( 'Location: '.str_replace('?'.$_SERVER['QUERY_STRING'],'',$_SERVER['REQUEST_URI']) );
} else { echo 'Sorry, this feature requires Zend Opcache newer than April 8th 2013'; }
exit;
}


?><!DOCTYPE html>
<html>
<head>
<title>OCP - Opcache Control Panel</title>
<meta name="ROBOTS" content="NOINDEX,NOFOLLOW,NOARCHIVE" />


<style type="text/css">
body {background-color: #fff; color: #000;}
body, td, th, h1, h2 {font-family: sans-serif;}
pre {margin: 0px; font-family: monospace;}
a:link,a:visited {color: #000099; text-decoration: none;}
a:hover {text-decoration: underline;}
table {border-collapse: collapse;}
.center {text-align: center;}
.center table { margin-left: auto; margin-right: auto; text-align: left;}
.center th { text-align: center !important; }
.middle {vertical-align:middle;}
td, th { border: 1px solid #000; font-size: 75%; vertical-align: baseline;}
h1 {font-size: 150%;}
h2 {font-size: 125%;}
.p {text-align: left;}
.e {background-color: #ccccff; font-weight: bold; color: #000; width:50%; white-space:nowrap;}
.h {background-color: #9999cc; font-weight: bold; color: #000;}
.v {background-color: #cccccc; color: #000;}
.vr {background-color: #cccccc; text-align: right; color: #000; white-space: nowrap;}
.b {font-weight:bold;}
.white, .white a {color:#fff;}

img {float: right; border: 0px;}
hr {width: 600px; background-color: #cccccc; border: 0px; height: 1px; color: #000;}
.meta, .small {font-size: 75%; }
.meta {margin: 2em 0;}
.meta a, th a {padding: 10px; white-space:nowrap; }
.buttons {margin:0 0 1em;}
.buttons a {margin:0 15px; background-color: #9999cc; color:#fff; text-decoration:none; padding:1px; border:1px solid #000; display:inline-block; width:5em; text-align:center;}
#files td.v a {font-weight:bold; color:#9999cc; margin:0 10px 0 5px; text-decoration:none; font-size:120%;}
#files td.v a:hover {font-weight:bold; color:#ee0000;}
.graph {display:inline-block; width:145px; margin:1em 0 1em 1px; border:0; vertical-align:top;}
.graph table {width:100%; height:150px; border:0; padding:0; margin:5px 0 0 0; position:relative;}
.graph td {vertical-align:middle; border:0; padding:0 0 0 5px;}
.graph .bar {width:25px; text-align:right; padding:0 2px; color:#fff;}
.graph .total {width:34px; text-align:center; padding:0 5px 0 0;}
.graph .total div {border:1px dashed #888; border-right:0; height:99%; width:12px; position:absolute; bottom:0; left:17px; z-index:-1;}
.graph .total span {background:#fff; font-weight:bold;}
.graph .actual {text-align:right; font-weight:bold; padding:0 5px 0 0;}
.graph .red {background:#ee0000;}
.graph .green {background:#00cc00;}
.graph .brown {background:#8B4513;}
</style>
<!--[if lt IE 9]><script type="text/javascript" defer="defer">
window.onload=function(){var i,t=document.getElementsByTagName('table');for(i=0;i<t.length;i++){if(t[i].parentNode.className=='graph')t[i].style.height=150-(t[i].clientHeight-150)+'px';}}
</script><![endif]-->
</head>


<body>
<div class="center">


<h1><a href="?">Opcache Control Panel</a></h1>


<div class="buttons">
<a href="?ALL=1">Details</a>
<a href="?FILES=1&GROUP=2&SORT=3">Files</a>
<a href="?RESET=1" onclick="return confirm('RESET cache ?')">Reset</a>
<?php if ( function_exists(CACHEPREFIX.'invalidate') ) { ?>
<a href="?RECHECK=1" onclick="return confirm('Recheck all files in the cache ?')">Recheck</a>
<?php } ?>
<a href="?" onclick="window.location.reload(true); return false">Refresh</a>
</div>


<?php


if ( !function_exists(CACHEPREFIX.'get_status') ) { echo '<h2>Opcache not detected?</h2>'; die; }


if ( !empty($_GET['FILES']) ) { echo '<h2>files cached</h2>'; files_display(); echo '</div></body></html>'; exit; }


if ( !(isset($_REQUEST['GRAPHS']) && !$_REQUEST['GRAPHS']) && CACHEPREFIX=='opcache_') { graphs_display(); if ( !empty($_REQUEST['GRAPHS']) ) { exit; } }


ob_start(); phpinfo(8); $phpinfo = ob_get_contents(); ob_end_clean();
// some info is only available via phpinfo? sadly buffering capture has to be used
if ( !preg_match( '/module\_Zend (Optimizer\+|OPcache).+?(\<table[^>]*\>.+?\<\/table\>).+?(\<table[^>]*\>.+?\<\/table\>)/s', $phpinfo, $opcache) ) { } // todo


if ( function_exists(CACHEPREFIX.'get_configuration') ) { echo '<h2>general</h2>'; $configuration=call_user_func(CACHEPREFIX.'get_configuration'); }


$host=function_exists('gethostname')?@gethostname():@php_uname('n'); if (empty($host)) { $host=empty($_SERVER['SERVER_NAME'])?$_SERVER['HOST_NAME']:$_SERVER['SERVER_NAME']; }
$version=array('Host'=>$host);
$version['PHP Version']='PHP '.(defined('PHP_VERSION')?PHP_VERSION:'???').' '.(defined('PHP_SAPI')?PHP_SAPI:'').' '.(defined('PHP_OS')?' '.PHP_OS:'');
$version['Opcache Version']=empty($configuration['version']['version'])?'???':$configuration['version'][CACHEPREFIX.'product_name'].' '.$configuration['version']['version'];
print_table($version);


if ( !empty($opcache[2]) ) { echo preg_replace('/\<tr\>\<td class\="e"\>[^>]+\<\/td\>\<td class\="v"\>[0-9\,\. ]+\<\/td\>\<\/tr\>/','',$opcache[2]); }


if ( function_exists(CACHEPREFIX.'get_status') && $status=call_user_func(CACHEPREFIX.'get_status') ) {
$uptime=array();
if ( !empty($status[CACHEPREFIX.'statistics']['start_time']) ) {
$uptime['uptime']=time_since($time,$status[CACHEPREFIX.'statistics']['start_time'],1,'');
}
if ( !empty($status[CACHEPREFIX.'statistics']['last_restart_time']) ) {
$uptime['last_restart']=time_since($time,$status[CACHEPREFIX.'statistics']['last_restart_time']);
}
if (!empty($uptime)) {print_table($uptime);}

if ( !empty($status['cache_full']) ) { $status['memory_usage']['cache_full']=$status['cache_full']; }

echo '<h2 id="memory">memory</h2>';
print_table($status['memory_usage']);
unset($status[CACHEPREFIX.'statistics']['start_time'],$status[CACHEPREFIX.'statistics']['last_restart_time']);
echo '<h2 id="statistics">statistics</h2>';
print_table($status[CACHEPREFIX.'statistics']);
}


if ( empty($_GET['ALL']) ) { meta_display(); exit; }

if ( !empty($configuration['blacklist']) ) { echo '<h2 id="blacklist">blacklist</h2>'; print_table($configuration['blacklist']); }


if ( !empty($opcache[3]) ) { echo '<h2 id="runtime">runtime</h2>'; echo $opcache[3]; }


$name='zend opcache'; $functions=get_extension_funcs($name);
if (!$functions) { $name='zend optimizer+'; $functions=get_extension_funcs($name); }
if ($functions) { echo '<h2 id="functions">functions</h2>'; print_table($functions); } else { $name=''; }


$level=trim(CACHEPREFIX,'_').'.optimization_level';
if (isset($configuration['directives'][$level])) {
echo '<h2 id="optimization">optimization levels</h2>';

$levelset=strrev(base_convert($configuration['directives'][$level], 10, 2));
$levels=array(
1=>'<a href="http://wikipedia.org/wiki/Common_subexpression_elimination">Constants subexpressions elimination</a> (CSE) true, false, null, etc.<br />Optimize series of ADD_STRING / ADD_CHAR<br />Convert CAST(IS_BOOL,x) into BOOL(x)<br />Convert <a href="http://www.php.net/manual/internals2.opcodes.init-fcall-by-name.php">INIT_FCALL_BY_NAME</a> + <a href="http://www.php.net/manual/internals2.opcodes.do-fcall-by-name.php">DO_FCALL_BY_NAME</a> into <a href="http://www.php.net/manual/internals2.opcodes.do-fcall.php">DO_FCALL</a>',
2=>'Convert constant operands to expected types<br />Convert conditional <a href="http://php.net/manual/internals2.opcodes.jmp.php">JMP</a> with constant operands<br />Optimize static <a href="http://php.net/manual/internals2.opcodes.brk.php">BRK</a> and <a href="<a href="http://php.net/manual/internals2.opcodes.cont.php">CONT</a>',
3=>'Convert $a = $a + expr into $a += expr<br />Convert $a++ into ++$a<br />Optimize series of <a href="http://php.net/manual/internals2.opcodes.jmp.php">JMP</a>',
4=>'PRINT and ECHO optimization (<a href="https://github.com/zend-dev/ZendOptimizerPlus/issues/73">defunct</a>)',
5=>'Block Optimization - most expensive pass<br />Performs many different optimization patterns based on <a href="http://wikipedia.org/wiki/Control_flow_graph">control flow graph</a> (CFG)',
9=>'Optimize <a href="http://wikipedia.org/wiki/Register_allocation">register allocation</a> (allows re-usage of temporary variables)',
10=>'Remove NOPs'
);
echo '<table width="600" border="0" cellpadding="3"><tbody><tr class="h"><th>Pass</th><th>Description</th></tr>';
foreach ($levels as $pass=>$description) {
$disabled=substr($levelset,$pass-1,1)!=='1' || $pass==4 ? ' white':'';
echo '<tr><td class="v center middle'.$disabled.'">'.$pass.'</td><td class="v'.$disabled.'">'.$description.'</td></tr>';
}
echo '</table>';
}


if ( isset($_GET['DUMP']) ) {
if ($name) { echo '<h2 id="ini">ini</h2>'; print_table(ini_get_all($name,true)); }
foreach ($configuration as $key=>$value) { echo '<h2>',$key,'</h2>'; print_table($configuration[$key]); }
exit;
}


meta_display();


echo '</div></body></html>';


exit;


function time_since($time,$original,$extended=0,$text='ago') {

$time = $time - $original;
$day = $extended? floor($time/86400) : round($time/86400,0);
$amount=0; $unit='';
if ( $time < 86400) {
if ( $time < 60)
{ $amount=$time; $unit='second'; }
elseif ( $time < 3600) { $amount=floor($time/60); $unit='minute'; }
else { $amount=floor($time/3600); $unit='hour'; }

}
elseif ( $day < 14)
{ $amount=$day; $unit='day'; }
elseif ( $day < 56)
{ $amount=floor($day/7); $unit='week'; }
elseif ( $day < 672) { $amount=floor($day/30); $unit='month'; }
else { $amount=intval(2*($day/365))/2; $unit='year'; }

if ( $amount!=1) {$unit.='s';}

if ($extended && $time>60) { $text=' and '.time_since($time,$time<86400?($time<3600?$amount*60:$amount*3600):$day*86400,0,'').$text; }

return $amount.' '.$unit.' '.$text;
}


function print_table($array,$headers=false) {
if ( empty($array) || !is_array($array) ) {return;}
echo '<table border="0" cellpadding="3" width="600">';
if (!empty($headers)) {
if (!is_array($headers)) {$headers=array_keys(reset($array));}
echo '<tr class="h">';
foreach ($headers as $value) { echo '<th>',$value,'</th>'; }
echo '</tr>';

}
foreach ($array as $key=>$value) {
echo '<tr>';
if ( !is_numeric($key) ) {
$key=ucwords(str_replace('_',' ',$key));
echo '<td class="e">',$key,'</td>';
if ( is_numeric($value) ) {
if ( $value>1048576) { $value=round($value/1048576,1).'M'; }
elseif ( is_float($value) ) { $value=round($value,1); }
}
}
if ( is_array($value) ) {
foreach ($value as $column) {
echo '<td class="v">',$column,'</td>';
}
echo '</tr>';
}
else { echo '<td class="v">',$value,'</td></tr>'; }
}
echo '</table>';
}


function files_display() {
$status=call_user_func(CACHEPREFIX.'get_status');
if ( empty($status['scripts']) ) {return;}
if ( isset($_GET['DUMP']) ) { print_table($status['scripts']); exit;}
$time=time(); $sort=0;
$nogroup=preg_replace('/\&?GROUP\=[\-0-9]+/','',$_SERVER['REQUEST_URI']);
$nosort=preg_replace('/\&?SORT\=[\-0-9]+/','',$_SERVER['REQUEST_URI']);
$group=empty($_GET['GROUP'])?0:intval($_GET['GROUP']); if ( $group<0 || $group>9) { $group=1;}
$groupset=array_fill(0,9,''); $groupset[$group]=' class="b" ';

echo '<div class="meta">

<a ',$groupset[0],'href="',$nogroup,'">ungroup</a> |
<a ',$groupset[1],'href="',$nogroup,'&GROUP=1">1</a> |
<a ',$groupset[2],'href="',$nogroup,'&GROUP=2">2</a> |
<a ',$groupset[3],'href="',$nogroup,'&GROUP=3">3</a> |
<a ',$groupset[4],'href="',$nogroup,'&GROUP=4">4</a> |
<a ',$groupset[5],'href="',$nogroup,'&GROUP=5">5</a>
</div>';

if ( !$group ) { $files =& $status['scripts']; }
else {
$files=array();
foreach ($status['scripts'] as $data) {
if ( preg_match('@^[/]([^/]+[/]){'.$group.'}@',$data['full_path'],$path) ) {
if ( empty($files[$path[0]])) { $files[$path[0]]=array('full_path'=>'','files'=>0,'hits'=>0,'memory_consumption'=>0,'last_used_timestamp'=>'','timestamp'=>''); }
$files[$path[0]]['full_path']=$path[0];
$files[$path[0]]['files']++;
$files[$path[0]]['memory_consumption']+=$data['memory_consumption'];

$files[$path[0]]['hits']+=$data['hits'];
if ( $data['last_used_timestamp']>$files[$path[0]]['last_used_timestamp']) {$files[$path[0]]['last_used_timestamp']=$data['last_used_timestamp'];}
if ( $data['timestamp']>$files[$path[0]]['timestamp']) {$files[$path[0]]['timestamp']=$data['timestamp'];}

}
}
}

if ( !empty($_GET['SORT']) ) {
$keys=array(
'full_path'=>SORT_STRING,
'files'=>SORT_NUMERIC,
'memory_consumption'=>SORT_NUMERIC,
'hits'=>SORT_NUMERIC,
'last_used_timestamp'=>SORT_NUMERIC,
'timestamp'=>SORT_NUMERIC
);
$titles=array('','path',$group?'files':'','size','hits','last used','created');
$offsets=array_keys($keys);
$key=intval($_GET['SORT']);
$direction=$key>0?1:-1;
$key=abs($key)-1;
$key=isset($offsets[$key])&&!($key==1&&empty($group))?$offsets[$key]:reset($offsets);
$sort=array_search($key,$offsets)+1;
$sortflip=range(0,7); $sortflip[$sort]=-$direction*$sort;
if ( $keys[$key]==SORT_STRING) {$direction=-$direction; }
$arrow=array_fill(0,7,''); $arrow[$sort]=$direction>0?' ▼':' ▲';
$direction=$direction>0?SORT_DESC:SORT_ASC;
$column=array(); foreach ($files as $data) { $column[]=$data[$key]; }
array_multisort($column, $keys[$key], $direction, $files);
}


echo '<table border="0" cellpadding="3" width="960" id="files">
<tr class="h">';
foreach ($titles as $column=>$title) {
if ($title) echo '<th><a href="',$nosort,'&SORT=',$sortflip[$column],'">',$title,$arrow[$column],'</a></th>';
}
echo ' </tr>';
foreach ($files as $data) {
echo '<tr>
<td class="v" nowrap><a title="recheck" href="?RECHECK=',rawurlencode($data['full_path']),'">x</a>',$data['full_path'],'</td>',
($group?'<td class="vr">'.number_format($data['files']).'</td>':''),
'<td class="vr">',number_format(round($data['memory_consumption']/1024)),'K</td>',
'<td class="vr">',number_format($data['hits']),'</td>',

'<td class="vr">',time_since($time,$data['last_used_timestamp']),'</td>',
'<td class="vr">',empty($data['timestamp'])?'':time_since($time,$data['timestamp']),'</td>
</tr>';
}
echo '</table>';
}


function graphs_display() {
$graphs=array();
$colors=array('green','brown','red');
$primes=array(223, 463, 983, 1979, 3907, 7963, 16229, 32531, 65407, 130987);
$configuration=call_user_func(CACHEPREFIX.'get_configuration');
$status=call_user_func(CACHEPREFIX.'get_status');


$graphs['memory']['total']=$configuration['directives']['opcache.memory_consumption'];
$graphs['memory']['free']=$status['memory_usage']['free_memory'];
$graphs['memory']['used']=$status['memory_usage']['used_memory'];
$graphs['memory']['wasted']=$status['memory_usage']['wasted_memory'];


$graphs['keys']['total']=$status[CACHEPREFIX.'statistics']['max_cached_keys'];

foreach ($primes as $prime) { if ($prime>=$graphs['keys']['total']) { $graphs['keys']['total']=$prime; break;} }
$graphs['keys']['free']=$graphs['keys']['total']-$status[CACHEPREFIX.'statistics']['num_cached_keys'];
$graphs['keys']['scripts']=$status[CACHEPREFIX.'statistics']['num_cached_scripts'];
$graphs['keys']['wasted']=$status[CACHEPREFIX.'statistics']['num_cached_keys']-$status[CACHEPREFIX.'statistics']['num_cached_scripts'];


$graphs['hits']['total']=0;
$graphs['hits']['hits']=$status[CACHEPREFIX.'statistics']['hits'];
$graphs['hits']['misses']=$status[CACHEPREFIX.'statistics']['misses'];
$graphs['hits']['blacklist']=$status[CACHEPREFIX.'statistics']['blacklist_misses'];
$graphs['hits']['total']=array_sum($graphs['hits']);


$graphs['restarts']['total']=0;
$graphs['restarts']['manual']=$status[CACHEPREFIX.'statistics']['manual_restarts'];
$graphs['restarts']['keys']=$status[CACHEPREFIX.'statistics']['hash_restarts'];
$graphs['restarts']['memory']=$status[CACHEPREFIX.'statistics']['oom_restarts'];
$graphs['restarts']['total']=array_sum($graphs['restarts']);


foreach ( $graphs as $caption=>$graph) {
echo '<div class="graph"><div class="h">',$caption,'</div><table border="0" cellpadding="0" cellspacing="0">';

foreach ($graph as $label=>$value) {
if ($label=='total') { $key=0; $total=$value; $totaldisplay='<td rowspan="3" class="total"><span>'.($total>999999?round($total/1024/1024).'M':($total>9999?round($total/1024).'K':$total)).'</span><div></div></td>'; continue;}
$percent=$total?floor($value*100/$total):''; $percent=!$percent||$percent>99?'':$percent.'%';
echo '<tr>',$totaldisplay,'<td class="actual">', ($value>999999?round($value/1024/1024).'M':($value>9999?round($value/1024).'K':$value)),'</td><td class="bar ',$colors[$key],'" height="',$percent,'">',$percent,'</td><td>',$label,'</td></tr>';
$key++; $totaldisplay='';
}
echo '</table></div>',"\n";
}
}


function meta_display() {
?>
<div class="meta">
<a href="http://files.zend.com/help/Zend-Server-6/content/zendoptimizerplus.html">directives guide</a> |
<a href="http://files.zend.com/help/Zend-Server-6/content/zend_optimizer+_-_php_api.htm">functions guide</a> |
<a href="https://wiki.php.net/rfc/optimizerplus">wiki.php.net</a> |
<a href="http://pecl.php.net/package/ZendOpcache">pecl</a> |
<a href="https://github.com/zend-dev/ZendOptimizerPlus/">Zend source</a> |
<a href="https://gist.github.com/ck-on/4959032/?ocp.php">OCP latest</a>
</div>
<?php
}
?>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: