使用本地的環境測試10萬次和 100萬次 緩衝的讀寫,測試環境和結果如下。
環境
Win7 x64 AMD7750雙核 記憶體8GApache 2.4.9PHP 5.5.12 ts vc11 memcache 2.2.7
代碼
functionconvert($size){$unit = array('b', 'kb', 'mb', 'gb', 'tb', 'pb'); return @round($size / pow(1024, ($i = floor(log($size, 1024)))), 2) . ' ' . $unit[$i];}functioncacheFile($key){$dir = 'cache'; if (!is_dir($dir) && !mkdir($dir)) { thrownewException(" 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;}functioncacheMem($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.9sec250kbMemcache 11sec250kb
結果 10萬次
花費時間 記憶體耗費File94s 251.18KBMemcache 逾時120s 報錯
Memcache 10萬次測試失敗,報錯內容如下
Warning: Memcache::connect(): in D:\localhost\speed.php online37Warning: Memcache::get(): No servers added to memcache connection in D:\localhost\speed.phpWarning: Memcache::set(): No servers added to memcache connection in D:\localhost\speed.php online41Fatal error: Maximum execution timeof120seconds exceeded in D:\localhost\speed.php online38
結論
memcache 用來做緩衝卻還沒有 直接File檔案快取快,之所以做這個測試,是因為面試的時候我回答自己並沒有使用這個memcache 來做緩衝,直接使用File檔案快取(單台伺服器),結果直接被技術官認定為是很菜鳥。但我通過這樣的測試,雖然是在win下面,可為什麼Memcahe效能還不如File ?
還是說我測試的方式存在錯誤? 求解 default.fu@foxmail.com
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。
以上就介紹了Memcache緩衝居然不如直接File檔案快取?,包括了方面的內容,希望對PHP教程有興趣的朋友有所協助。