php使用apc为include大文件数组提速

前言 最近在重写某系统, 有个地方需要include一大数组文件,差不多有1.2M,PHP程序每次跑到这块代码都需要从硬盘读取内容,站点访问量达了势必会造成过量的IO. 考虑使用 redis,memcache等KV存储,但是担心IO过大造成网络阻塞。那安装到本地呢,每台都需要安装岂不是太麻烦了.于是觉得尝试将数组存入本机内存中. eaccelerator与APC二选一,eaccelerator 0.6.5.1之后的版本不支持eaccelerator_put方法,索性直接使用apc,如何安装以及 如何配置APC我就不详细讲解了. 例子很简单,废话太多,进入正题. 简介 APC全称Alternative PHP Cache是一个免费开源的php缓存插件,它的目标是提供一个自由,开放和强大的框架用于缓存和优化PHP中间代码. APC配置 php.ini
[apc]
extension = php_apc.dll
apc.enabled = on 
apc.cache_by_default = off  //一定要off,否则所有php都会被cache
apc.shm_segments = 2
apc.shm_size = 128M // 单位M或者G,网上很多没写,会报错
apc.ttl = 7200
apc.user_ttl = 7200
apc.num_files_hint = 1024
apc.write_lock = On
apc.gc_ttl=3600
apc.ttl=0
apc.max_file_size=2M //最大单个文件大小
APC VS include方法 大文件数组内容: arrFile.php
<?php
 $arr = array(
 "aaaa"=>11,
 "BBBBB"=>11,
 ....忽略几万个
 "CCCCC"=>11
 )
include文件代码片段
<?php
    include_once 'arrFile.php';
    print_r($arr);
?>
APC加速文件代码片段
<?php
    $arr=apc_fetch('key'); # 读取apc缓存
    $arr=unserialize($arr);
?>
include与apc性能对比 全部代码如下
<?php
/**
 * 站点:www.ttlsa.com
 * 作者:凉白开
 * QQ群:3951405 
 */
# include array file
$ti1 = microtime ( true );
include_once 'arrFile.php';
$ti2 = microtime ( true );
$ti3=(($ti2 - $ti1) * 1000);
echo "<B>加载文件数组耗时</B>:".$ti3. 'ms<br>';

# apc save
$arrSeri=serialize($arr);   //将上面include的数组序列化
apc_add("key",$badSeri,300); //序列化后的文件保存到apc缓存中,键为key,过期时间300秒
# 写入一次即可,后续都直接在内存中获取.

# apc fetch
$ta1 = microtime ( true );
$a=apc_fetch('key'); // 从apc中取出内容
$arr=unserialize($a);
$ta2 = microtime ( true );
$ta3=(($ta2 - $ta1) * 1000);
echo "<B>加载apc数组耗时</B>:".$ta3 . 'ms<br>';

# result 对比结果
echo round(($ti3-$ta3)/$ta3*100,2) .'%'; // APC比include快百分之几
?>
测试截图如下: [caption id="attachment_2848" align="alignnone" width="526"] apc与include速度比较[/caption] 最后 代码很简单,简单的将apc当做 memcached来使用,相比include时间要缩短2倍左右,最慢的情况下时间也缩短一倍. 下回测试redis存储大数组需要多少时间. 本文不是告诉大家非要使用apc、使用apc读写大数组不一定是最好的方法,但是这个方法或许大家的工作可以用上,这边抛出的仅仅是一个思路,望大家可以用上. 转载请注明出处:http://www.ttlsa.com/html/2847.html

转载于:https://my.oschina.net/766/blog/211211

猜你喜欢

转载自blog.csdn.net/weixin_34162401/article/details/91492937