Demonstration code that uses cache APC more efficiently than Memcached on the same server_PHP tutorial

WBOY
Release: 2016-07-21 15:40:54
Original
856 people have browsed it

复制代码 代码如下:

$memcachehost = 'localhost';
$memcacheport = '11211';
function microtime_float(){
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
function runtime($t1){
return number_format((microtime_float() - $t1)*1000, 4).'ms';
}
$starttime = microtime_float();
$cache_time = '30';
echo "init=====".runtime($starttime).'
';

$sql = "SELECT * FROM hx WHERE id = 10006";
$mem_sql_key = md5($sql);

$t1 = microtime_float();
echo "APC_read=====";
$arrs = apc_fetch($mem_sql_key);
echo runtime($t1).'
';

$t1 = microtime_float();
apc_store($mem_sql_key.'_test', $arrs, $cache_time);
echo "APC_write=====";
echo runtime($t1).'
';

$t1 = microtime_float();
$mem = new Memcache;
$mem->connect($memcachehost, $memcacheport);
echo "MEM_connet=====".runtime($t1).'
';

$t1 = microtime_float();
$arrs = $mem->get($mem_sql_key);
echo "MEM_read=====";
echo runtime($t1).'
';
$t1 = microtime_float();
$mem->set($mem_sql_key.'_test',$arrs,0,$cache_time);
echo "MEM_write=====";
echo runtime($t1).'
';
?>

预先把这句SQL的结果在apc和memcached中都缓存了,然后测试读写速度。
在本机windows上结果:
init=====0.0341ms
APC_read=====0.0439ms
APC_write=====0.0920ms
MEM_connet=====11.0571ms
MEM_read=====0.2630ms
MEM_write=====0.2270ms

在服务器上linux上结果:
init=====0.0131ms
APC_read=====0.0520ms
APC_write=====0.0489ms
MEM_connet=====0.0501ms
MEM_read=====0.1030ms
MEM_write=====0.0801ms

当然反复刷新会有不同的值,这里只是取了一个较平均的值。
win下的不具备什么参考性,主要看linux上的结果。
不算connent时间,大概读写的速度apc都比memcached快上一倍左右。算上memcache_connect的时间,也就是快二倍。
APC即可以实现php文件的opcode缓存,也可以实现user cache,实在是个好东西。

所以,如果当网站规模还小的时候,所有功能可以在一台服务器上完成时,那么缓存的方案首选应该就是APC,不用考虑memcached。但如果考虑到网站规模会不断扩大,这点时间的性能差异其实可以忽略不计的,就应该部署memcached了。
另外,跨服务器使用memcached,最好要使用内网。不然的话,受路由的影响,memcached经常会连接超时(超过100ms),而且会凭空多出来两倍的宽带流量。

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/321268.htmlTechArticle复制代码 代码如下: ?php $memcachehost = 'localhost'; $memcacheport = '11211'; function microtime_float(){ list($usec, $sec) = explode(" ", microtime()); return ((float)$use...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!