php測試代碼執行消耗的記憶體和時間

來源:互聯網
上載者:User

我們先來看看microtime 和 memory_get_usage函數用法吧

義和用法

microtime() 函數返回當前 Unix 時間戳記和微秒數。

文法

microtime(get_as_float)參數 描述
get_as_float 如果給出了 get_as_float 參數並且其值等價於 TRUE,該函數將返回一個浮點數。

例子

 代碼如下 複製代碼
<?php
echo(microtime());
?>

輸出:

0.25139300 1138197510

一,函數原型

int memory_get_usage ([ bool $real_usage=false ] )

二,版本相容

PHP 4 >= 4.3.2,PHP 5

三,基礎用法與執行個體

1,擷取當前的記憶體消耗量

 代碼如下 複製代碼

<?php
echo memory_get_usage();
$var=str_repeat(www.111cn.net,10000);
echo memory_get_usage();
unset($var);
echo memory_get_usage();
?>

結果輸出:62328 122504 62416

說明:memory_get_usage() 函數輸出的數值為 bytes 單位

2,格式化 memory_get_usage() 結果以 KB 為單位輸出

 

 代碼如下 複製代碼
<?php
function convert($size){
 $unit=array('b','kb','mb','gb','tb','pb');
 return @round($size/pow(1024,($i=floor(log($size,1024)))),2).' '.$unit[$i];
}
echo convert(memory_get_usage(true));
?>

265KB

好了兩個函數基本介紹完了,下面我來看一個測試執行個體

 

 代碼如下 複製代碼

<?php

$t1 = microtime(true);
$m1 = memory_get_usage(true);
echo fixByte($m1). '<br />';

/*↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓*/

/*↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑*/

$t2 = microtime(true);
$m2 = memory_get_usage(true);
echo '<br />' . fixByte($m2). '<br />';

echo '<hr >';
echo 'time ' . round(($t2 - $t1), 4) .'<br />';
echo 'mem ' . fixByte($m2 - $m1) .  '<br />';

/**
 * 格式化位元組為合適的數值
 * @param int $byte 位元組數
 * @param string $string 格式化的可讀性強的位元組數
 */
function fixByte($byte, $string = true, $dot_num = 9) {
 $ret = array(
   'data'=>$byte,
   'danwei'=>'Byte',
 );

 if ($byte < 1024) {

 } else if ($byte < 1024*1024) {
  $ret['data'] = round($byte / 1024, $dot_num);
  $ret['danwei']='K';
 } else if ($byte < 1024*1024*1024) {
  $ret['data'] = round($byte / (1024*1024), $dot_num);
  $ret['danwei']='M';
 } else if ($byte < 1024*1024*1024*1024) {
  $ret['data'] = round($byte / (1024*1024*1024), $dot_num);
  $ret['danwei']='GB';
 } else if ($byte < 1024*1024*1024*1024*1024) {
  $ret['data'] = round($byte / (1024*1024*1024*1024), $dot_num);
  $ret['danwei']='TB';
 }

 if ($string) {
  $ret = $ret['data'] . ' ' . $ret['danwei'];
 }

 return $ret;
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.