Date/Time Processing with PHP - Race Against Time
(Page 4 of 7 )
If you don't like mktime(), you can also use the time() function, which returns the current timestamp (note that you cannot use this function to generate arbitrary timestamps, as is possible with mktime()).
If you need greater accuracy in your timestamp, take a look at the microtime() function, which returns a timestamp in seconds, together with an additional microsecond component. These two values can be added together to obtain a more precise timestamp value. Like time(), this function too cannot be used with arbitrary dates and times - it only returns a timestamp for the current instant.
The microtime() function is particularly useful when you need to time events accurately, or when you need an arbitrary, unique number to seed PHP's random number generator. Here's an example of the former:
<?
// function to calculate timestamp in microseconds
function tscalc()
{
// split returned timestamp
$arr = explode(" ", microtime());
// add microseconds to seconds
// to generate more precise timestamp
return $arr[0] + $arr[1];
}
// start time
$start = tscalc();
// do something
// over here, run a loop
$count = 0;
$x = 0;
while ($count < 500)
{
$x = $x + $count;
$count++;
}
// end time
$end = tscalc();
echo "Started at $start";
echo "Ended at $end";
echo "Total processing time was " . ($end-$start);
?>And here's an example of the latter:
<?
// function to calculate timestamp in microseconds
function tscalc()
{
// split returned timestamp
$arr = explode(" ", microtime());
// add microseconds to seconds
// to generate more precise timestamp
return $arr[0] + $arr[1];
}
// seed random number generator
srand(tscalc());
// get a random number
echo rand();
?>Next: When Looks Do Matter >>
More PHP Articles
More By The Disenchanted Developer, (c) Melonfire