0

I'm wondering if there is a way to know the time each function takes to execute within my php script ?

The script contain functions like (if conditions - for loop - connections to the DB using PDO).

for example I have something like that :

<?php
$link = $_POST['url'];
$links = array();

for($i = 1; i < 9; i++){
  array_push($links , $link . 'page' . $i);
}

foreach($links as $lin){
  //PDO connection to the DB , It's not written right
  $statement = 'SELECT * from links WHERE link = :zlink';
  zlink = $lin;
  $count = $statement->rowCount();
  if($count > 1){
    // do something
  }else{
    'INSERT INTO links WHERE link = :mlink';
    mlink = $lin;

    file_put_contents();
  }
}

and more other functions , So is it possible to know how much each of these functions take? and what takes much time ?

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
Joe
  • 43
  • 7
  • 1
    Yes, you could just throw in some `microtime()` snapshots before/after the code you want to check and compare the times. For proper debugging though you should look into Xdebug profiling. example: https://confluence.jetbrains.com/display/PhpStorm/Profiling+PHP+applications+with+PhpStorm+and+Xdebug – JimL Nov 03 '17 at 17:10
  • Check out https://stackoverflow.com/questions/6245971/accurate-way-to-measure-execution-times-of-php-scripts – acaputo Nov 03 '17 at 17:11
  • If you're using xdebug, you can enable profiling and cachegrind the fiel generated by that profiling to get details of the number of function calls, their duration, etc – Mark Baker Nov 03 '17 at 17:12

1 Answers1

0

If you want to accomplish this without using external libraries, add a function to your code like:

function splittime( $flag = NULL, $msg = ‘’, $output = TRUE ) {

  $ts = microtime( TRUE );

  if ( $output ) {

    if ( $flag ) {
      echo ( round( ( $ts - $flag ), 3 ) ) . " seconds - ";
    }

    echo $msg . ": " . date( 'H:i:s', $ts ) . ":" . ( round( ( $ts - intval( $ts ) ), 3 ) * 1000 ) . "<br><br>";

  }

  return $ts;

}

The first time you call the function in your script (or inside another function), call it like this:

$flag = splittime();

With each subsequent call, use this:

$flag = splittime( $flag );
Ben Shoval
  • 1,732
  • 1
  • 15
  • 20