Question

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

Was it helpful?

Solution

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

OTHER TIPS

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()

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.

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top