1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > PHP-file redis apcu yac缓存效率简单对比

PHP-file redis apcu yac缓存效率简单对比

时间:2019-03-23 06:50:50

相关推荐

PHP-file redis apcu yac缓存效率简单对比

背景:

在工作中,编写一个脚本管理类,默认情况下会while(true)一直运行,该类中有个检查维护模式的行为,如果开启了维护模式,脚本就停止。因为每次在循环体内的首行去检查,如果检查频率过高,也是很高的一个访问量,所以就针对php常用到的缓存,做了简单的基准测试。

代码示例:

<?php// 测试数据$identifier = uniqid('demo_', false);// 文件缓存$cacheFile = '/upload/test/' . $identifier;!is_dir(dirname($cacheFile)) && mkdir(dirname($cacheFile), 0755, true);file_put_contents($cacheFile, microtime(true));function fileCacheExists($identifier){return file_exists('/upload/test/' . $identifier);}// Redis缓存$redis = new Redis();$redis->connect('192.168.1.8', 6379);$redis->set($identifier, 1, 30);function redisCacheExists($identifier){global $redis;return $redis->exists($identifier);}// APCu缓存apcu_add($identifier, 1, 30);function apcuCacheExists($identifier){return apcu_exists($identifier);}// YAC缓存$yac = new Yac();$yac->set($identifier, 1, 30);function yacCacheExists($identifier){global $yac;return $yac->get($identifier) !== false;}$cacheKinds = ['file','redis','apcu','yac',];// 基准测试$iterations = 10000;for ($j = 0, $count = \count($cacheKinds); $j < $count; $j++) {$func = sprintf('%sCacheExists', $cacheKinds[$j]);$counter = 0;$start = microtime(true);for ($i = 0; $i < $iterations; $i++) {$counter += $func($identifier);}$end= microtime(true);$costTime = $end - $start;// 输出结果echo sprintf('%s counter: %d' . PHP_EOL, $cacheKinds[$j], $counter);echo sprintf('%s cache cost time: %f seconds' . PHP_EOL, $cacheKinds[$j], $costTime);echo PHP_EOL;}?>

结果:

file counter: 10000file cache cost time: 0.018699 secondsredis counter: 10000redis cache cost time: 9.573377 secondsapcu counter: 10000apcu cache cost time: 0.004432 secondsyac counter: 10000yac cache cost time: 0.005169 seconds

分析:

以上测试是在docker环境中,redis花费时间最长,感觉主要原因在于建立连接,网络通信传输上。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。