0

If you want to calculate the time particular PHP script has been running you do it as following:

//Remember beginning time of the script
define("START_TIME", time());

//Do some loop or whatever
   ...

//At the end, calculate the difference of start and current time
echo "This script has been running for ".(time() - START_TIME)."\n";

Well, this is all nice, but imagine you're making a class/library, that might be included later in the script and that needs to calculate the runtime too.

Is there a function in PHP that would give me the timestamp when the script was launched - or a function that would allow me to deduct that?
This is what I need:

class Blah {
    public getRuntime() {
        static $startTime = get_start_time_magic_function();
        return time() - $startTime;
    }
}

My reason to require is, that I have a "infinite" loop in a class, that should automatically end when execution limit is going to take effect. If the script was killed by PHP, that would cause harm to processed data.

Tomáš Zato
  • 50,171
  • 52
  • 268
  • 778
  • http://stackoverflow.com/questions/535020/tracking-the-script-execution-time-in-php – juanrpozo Mar 01 '14 at 20:40
  • @juanrpozo I have read that post already before. – Tomáš Zato Mar 01 '14 at 21:19
  • 1
    How about [`$_SERVER['REQUEST_TIME']`](http://www.php.net/manual/en/reserved.variables.server.php) or (from PHP 5.4.0 on) `$_SERVER['REQUEST_TIME_FLOAT']`? While these might not technically by the script starting timestamp per se, I think the value should be close enough for most use cases. – CBroe Mar 01 '14 at 22:07
  • But I’m not sure if the actual problem you are trying to solve here _should_ be solved by looking at execution times/start timestamps … especially since you say the script being killed due to max_execution_time would _“cause harm to processed data”_ – I think this is not a case for checking “do I still have more time?”, but rather for a re-write of the script to a more robust data processing. – CBroe Mar 01 '14 at 22:09
  • 1
    What do you imagine being more robust data processing, may I ask? – Tomáš Zato Mar 01 '14 at 22:40

2 Answers2

1

Quoting from http://php.net/manual/en/function.microtime.php (Example #3):

<?php
// Randomize sleeping time
usleep(mt_rand(100, 10000));

// As of PHP 5.4.0, REQUEST_TIME_FLOAT is available in the $_SERVER superglobal array.
// It contains the timestamp of the start of the request with microsecond precision.
$time = microtime(true) - $_SERVER["REQUEST_TIME_FLOAT"];

echo "Did nothing in $time seconds\n";
?>
jor
  • 2,058
  • 2
  • 26
  • 46
-1
define("START_TIME", time());
define("MAX_DURATION", 3);
while (true) {
    $current_duration = time() - START_TIME;

    // do your stuff here

    if($current_duration >= MAX_DURATION) {
        echo "This script has been running for ". $current_duration ." seconds \n";
        break;
    }
}
Pascal Le Merrer
  • 5,883
  • 20
  • 35