Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

best way to measure (and refine) performance with PHP?

Tags:

php

testing

A site I am working with is starting to get a little sluggish, and I would like to refine it. I think the problem is with the PHP, but I can't be sure. How can I see how long functions are taking to perform?

like image 317
Mild Fuzz Avatar asked Oct 07 '10 09:10

Mild Fuzz


People also ask

How does PHP calculate speed?

Use timestamp function to measure the speed of code. The timestamp function placed twice in a program one at starting of program and another at end of the program. Then the time difference between end time and start time is the actual speed of code.


3 Answers

If you want to test the execution time :

<?php
    $startTime = microtime(true);  
    // Your content to test
    $endTime = microtime(true);  
    $elapsed = $endTime - $startTime;
    echo "Execution time : $elapsed seconds";
?>
like image 123
Spilarix Avatar answered Sep 28 '22 19:09

Spilarix


Try the profiler feature in XDebug or Zend Debugger?

like image 39
Joyce Babu Avatar answered Sep 28 '22 18:09

Joyce Babu


Two things you can do. place Microtime calls everywhere although its not convenient if you want to test more than one function. So there is a simpler way to do it a better solution if you want to test many functions which i assume you would like to do. just have a class (click on link to follow tutorial) where you can test how long all your functions take. Rather than place microtime everywhere. you just use this class. which is very convenient

http://codeaid.net/php/calculate-script-execution-time-%28php-class%29

the second thing you can do is to optimize your script is by taking a look at the memory usage. By observing the memory usage of your scripts, you may be able optimize your code better.

PHP has a garbage collector and a pretty complex memory manager. The amount of memory being used by your script. can go up and down during the execution of a script. To get the current memory usage, we can use the memory_get_usage() function, and to get the highest amount of memory used at any point, we can use the memory_get_peak_usage() function. view plaincopy to clipboardprint?

   echo "Initial: ".memory_get_usage()." bytes \n";  
   /* prints 
   Initial: 361400 bytes 
   */  

   // let's use up some memory  
   for ($i = 0; $i < 100000; $i++) {  
       $array []= md5($i);  
   }  

  // let's remove half of the array  
  for ($i = 0; $i < 100000; $i++) {  
     unset($array[$i]);  
  }  

  echo "Final: ".memory_get_usage()." bytes \n";  
  /* prints 
  Final: 885912 bytes 
  */  

  echo "Peak: ".memory_get_peak_usage()." bytes \n";  
  /* prints 
  Peak: 13687072 bytes 
  */  

http://net.tutsplus.com/tutorials/php/9-useful-php-functions-and-features-you-need-to-know/

PK

like image 32
Pavan Avatar answered Sep 28 '22 20:09

Pavan