1
votes

I have a time consuming script, and I want to periodically log it execution time. How do I find out the current execution time?

4

4 Answers

2
votes

The symfonian way to log execution times is using the timer manager that comes with symfony.

//Get timer instance called 'myTimer'.
$timer = sfTimerManager::getTimer('myTimer');
//Start timer.
$timer->startTimer();
// Do things
...
// Stop the timer and add the elapsed time
$timer->addTime();

This timer will be saved into any logger you have configured with your symfony. By default symfony has the sfWebDebugLogger for the DEV environment but you can create your own and configure it in the factories.yml file.

The nice thing about this logger is that it logs also the number of calls to the timer.

0
votes

Why not use date('Y-m-d H:i:s') and log that... and/or calculate difference from a start time obtained with date() as well?

0
votes

Think about what you are asking, each action is logged in symfony log (root/log/app_name_[env].log). This logging is done once the operation has ended, (there is no easy way to figure out the execution time of a thread executing a php from php). You could try messing up with code and add code in order to log at certain points of the code, the current execution time, something like:

$init = microtime();
log("Process started at:". $init);
foreach($this->getLotsOfRecords() as $index=>$record)
{
  $start = microtime();
  log ($index." record started at".microtime());
  [do stuff]
  $end = microtime();
  log ($index." record ended at". $end . " time elapsed: ". ($start - $end));
}
$last = microtime();
log("Total elapsed time is: ". ($init - $last));

This is pseudo code but i believe you can figure out the rest, hope this helps!

0
votes

I ended up writing my own static class:

class Timer
{
  protected static $start = null;

  public static function getDuration($format = '%H:%I:%S')
  {
    $now = new DateTime();

    if (!self::$start)
    {
      self::$start = new DateTime();
    }
    $period = $now->diff(self::$start);

    return $period->format($format);
  }
}

And logging it in partial (that is looped):

<?php $logger->log(sprintf("Duration: %s", $duration = Timer::getDuration())) ?>