views:

330

answers:

5

I have noticed that regardless of a given script's execution time, every date() call will return the same timestamp regardless of where the function is called within the script. It looks like it just returns the time at which the script first started executing.

For logging purposes, it would be extremely useful to be able to get incremental timestamps from within a script. Is this possible? Is there a way to do this that is relatively lightweight?

Edit: Would the example for the microtime() function suggests it might do this. Can anyone confirm?

Update: microtime() does work, but I cannot format it with the date() function because date() only accepts timestamps as integers (so no microseconds). How can I get a properly formatted date from the value returned by microtime() ?

+1  A: 

http://us.php.net/microtime gives me different times within the same script.

ceejayoz
A: 

You can use the Pear Benchmarking package for getting timing and profiling information.

CMS
+1  A: 

I ran this code on my machine:

<?php
$time_start = time();

sleep(2);

$time_end = time();

print 'Start: ' . date("m/d/Y @ g:i:sA", $time_start) . '<br>';
print 'End: ' . date("m/d/Y @ g:i:sA", $time_end);
?>

And it output:

Start: 10/23/2008 @ 3:12:23PM
End: 10/23/2008 @ 3:12:25PM

Leading me to believe time() does not just return the time when execution started.

Paolo Bergantino
+2  A: 

First of all, date() is used to format a timestamp - it's just the default behaviour that it'll use the current timestamp, when date() is called without second parameter. The timestamp used will be the timestamp the moment the function is called - calling date('Y-m-d') is the same as calling date('Y-m-d', time()) where time() will give you the

[...] the current time measured in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT).

You only get the same timestamp every time you call date() because your script is too fast and runs within one second resulting in no timestamp-change.

To address your second problem of formatting the microtime() return value, you can do the following (untested)

function formatTime($microtime, $format)
{
    list($timestamp, $fraction) = explode('.', $microtime);
    return date($format, (int)$timestamp) . '.' . $fraction;
}

The value given to $microtime should be a float, which you get when you pass true as a parameter to microtime()

Stefan Gehrig
A: 

I wonder if it depends on the version of PHP being used? My recollection was that time() returned the timestamp of the start of the request, but I see in the manual, that is wrong.

The note says "Timestamp of the start of the request is available in $_SERVER['REQUEST_TIME'] since PHP 5.1." Does this imply that prior to PHP 5.1, time() returned the timestamp at the start of the request?

Michelle