php中用缓存与不用缓存性能测试
在未看到这篇文章之前我们一般不会对于缓存这么看重,经过测试之后我们发现使用文件缓存比直接使用数据库要快几倍,下面测试是6倍之多,下面一起来看看吧.
在Thinkphp项目中测试各种环境下的程序执行时间,不使用缓存,代码如下:
<?php
header("content-type:text/html;charset=utf-8");
$starttime = caltime(); //开始时间
$articles = array();
//循环取出500条文章信息
for ($i = 0; $i < 100; $i++) {
$sql = "select a.*,c.* from blog_article as a,blog_category as c where a.reid=c.id limit 0,5";
$articles = array_merge($articles, M('article')->query($sql));
} //开源代码phprm.com
$overtime = caltime(); //结束时间
echo '不使用缓存条件下程序执行时间是:' . ($overtime - $starttime) . '秒';
?>结果:不使用缓存条件下程序执行时间是:0.0600001811981秒,文件缓存,代码如下:
<?php
header("content-type:text/html;charset=utf-8");
$starttime = caltime(); //开始时间
$articles = S('articles');
if (!$articles) {
$articles = array();
//循环取出500条 www.phprm.com 文章信息
for ($i = 0; $i < 100; $i++) {
$sql = "select a.*,c.* from blog_article as a,blog_category as c where a.reid=c.id limit 0,5";
$articles = array_merge($articles, M('article')->query($sql));
}
S('articles', $articles, 60);
}
$overtime = caltime(); //结束时间
echo '使用文件缓存条件下程序执行时间是:' . ($overtime - $starttime) . '秒';
?>结果:使用文件缓存条件下程序执行时间是:0.00999999046326秒,代码如下:
<?php
header("content-type:text/html;charset=utf-8");
$starttime = caltime(); //开始时间
$mem = new Memcache();
if (!$mem->connect('127.0.0.1', 11211)) {
echo '连接失败';
}
$articles = $mem->get('articles');
if (!$articles) {
$articles = array();
//循环取出500条文章信息
for ($i = 0; $i < 100; $i++) {
$sql = "select a.*,c.* from blog_article as a,blog_category as c where a.reid=c.id limit 0,5";
$articles = array_merge($articles, M('article')->query($sql));
}
$mem->set('articles', $articles, MEMCACHE_COMPRESSED, 60);
}
$overtime = caltime(); //结束时间
echo '使用memcache缓存条件下程序执行时间是:' . ($overtime - $starttime) . '秒';
?>结果:使用memcache缓存条件下程序执行时间是:0.00999999046326秒,代码如下:
<?php
header("content-type:text/html;charset=utf-8");
$starttime = caltime(); //开始时间
$redis = new Redis();
$redis->connect('127.0.0.1', '6379');
if (!$redis) {
echo '连接失败';
}
$articles = $redis->get('articles');
if (!$articles) {
$articles = array();
//循环取出500条www.phprm.com文章信息
for ($i = 0; $i < 100; $i++) {
$sql = "select a.*,c.* from blog_article as a,blog_category as c where a.reid=c.id limit 0,5";
$articles = array_merge($articles, M('article')->query($sql));
}
$redis->setex('articles', 60, $articles);
}
$overtime = caltime(); //结束时间
echo '使用redis缓存条件下程序执行时间是:' . ($overtime - $starttime) . '秒';
?>结果:使用redis缓存条件下程序执行时间是:0.00999999046326秒,可见使用缓存的条件下,程序的执行速度比不使用缓存的时候快了6倍,但是不同缓存由于数据不是特别庞大,几乎没有什么差别.
永久地址:http://www.phprm.com/develop/fs4821.html
转载随意~请带上教程地址吧^^