php memcache内存大小,PHP缓存:Memcache 不如 直接File文件缓存吗

使用本地的环境测试10万次和 100万次 缓存的读写,测试环境和结果如下。

环境

Win7 x64 AMD7750双核 内存8G

Apache 2.4.9

PHP 5.5.12 ts vc11

memcache 2.2.7

代码

function convert($size)

{

$unit = array('b', 'kb', 'mb', 'gb', 'tb', 'pb');

return @round($size / pow(1024, ($i = floor(log($size, 1024)))), 2) . ' ' . $unit[$i];

}

function cacheFile($key)

{

$dir = 'cache';

if (!is_dir($dir) && !mkdir($dir)) {

throw new Exception(" can't make dir $dir");

}

$filepath = $dir . DIRECTORY_SEPARATOR . sprintf('%x', crc32($key));

if (!(file_exists($filepath) && ($data = file_get_contents($filepath)) && !empty($data))) {

$data = date('Y-m-d H:i:s');

file_put_contents($filepath, $data);

}

return $data;

}

function cacheMem($key)

{

$mem = new Memcache();

$mem->connect('127.0.0.1', 11211);

$data = $mem->get($key);

if (empty($data)) {

$data = date('Y-m-d H:i:s');

$mem->set($key, $data);

}

return $data;

}

$t1 = microtime(true);

$i = 0;

$limit = 1000 * 100; //10 万次

$data = null;

while ($i < $limit) {

// $data = cacheFile($i);

$data = cacheMem($i);

$i++;

}

$timeUse = microtime(true) - $t1;

$arr = [

'cost' => sprintf('%.7fs', $timeUse),

'mem' => convert(memory_get_usage())

];

var_dump($arr);

结果 1万次

花费时间 内存耗费

File 1.9 sec 250kb

Memcache 11 sec 250kb

结果 10万次

花费时间 内存耗费

File 94s 251.18KB

Memcache 超时120s 报错

Memcache 10万次测试失败,报错内容如下

Warning: Memcache::connect(): in D:\localhost\speed.php on line 37

Warning: Memcache::get(): No servers added to memcache connection in D:\localhost\speed.php

Warning: Memcache::set(): No servers added to memcache connection in D:\localhost\speed.php on line 41

Fatal error: Maximum execution time of 120 seconds exceeded in D:\localhost\speed.php on line 38

结论

memcache 用来做缓存却还没有 直接File文件缓存快,之所以做这个测试,是因为面试的时候我回答自己并没有使用这个memcache 来做缓存,直接使用File文件缓存,结果直接被技术官认定为是初级程序员。但我通过这样的测试,虽然是在win下面,可为什么Memcahe性能还不如File ?

还是说我测试的方式存在错误?

2015-8-21 20:52:17

改进后,真的速度快了N倍! 10万毫无压力。17.18 sec 265KB内存

function cacheMem($key)

{

static $mem = null;

if ($mem === null) {

$mem = new Memcache();

$mem->connect('127.0.0.1', 11211);

}

$data = $mem->get($key);

if (empty($data)) {

$data = date('Y-m-d H:i:s');

$mem->set($key, $data);

}

return $data;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值