【问题标题】:Is there is a way to know how much time PHP functions that consists a script take?有没有办法知道包含脚本的 PHP 函数需要多少时间?
【发布时间】:2018-04-16 11:56:39
【问题描述】:

我想知道是否有办法知道每个函数在我的 php 脚本中执行所需的时间?

脚本包含类似(if 条件 - for 循环 - 使用 PDO 连接到 DB)等函数。

例如我有类似的东西:

<?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();
  }
}

还有更多其他功能,那么是否有可能知道这些功能中的每一个需要多少?什么需要很多时间?

【问题讨论】:

  • 是的,您可以在要检查的代码之前/之后添加一些microtime() 快​​照并比较时间。为了进行正确的调试,您应该查看 Xdebug 分析。例如:confluence.jetbrains.com/display/PhpStorm/…
  • 如果您使用的是 xdebug,您可以启用 profiling 并缓存该 profiling 生成的字段,以获取函数调用次数、持续时间等详细信息

标签: php performance time


【解决方案1】:

如果您想在不使用外部库的情况下完成此操作,请在您的代码中添加一个函数,例如:

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;

}

第一次在脚本中(或在另一个函数中)调用函数时,这样调用它:

$flag = splittime();

每次后续调用,都使用这个:

$flag = splittime( $flag );

【讨论】:

    猜你喜欢
    • 2019-03-21
    • 1970-01-01
    • 2013-05-21
    • 1970-01-01
    • 2020-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多