Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Measuring time

Status
Not open for further replies.

ushtabalakh

Programmer
Jun 4, 2007
132
Hi, I have made the following functions

To measure how much time it takes for apache to execute my codes, but it doesn't work properly, can someone tell me why?

Code:
<?php
$starttime =  microtime(true);

usleep(100);
$starttime = ShowTime($startTime, "step 1");

usleep(400);
$starttime = ShowTime($startTime, "step 2");
usleep(500);
$starttime = ShowTime($startTime, "step 3");
usleep(600);
$starttime = ShowTime($startTime, "step 4");
usleep(700);
$starttime = ShowTime($startTime, "step 5");




function ShowTime($startTime, $Message)
{
	$time_end = microtime(true);
	$time = $time_end - $time_start;
	echo $Message . " took " . $time . " seconds.<br/>";
	return microtime(true);
}

function microtime_float()
{
    list($usec, $sec) = explode(" ", microtime());
    return ((float)$usec + (float)$sec);
}

?>


This is the output:
step 1 took 1207904003.4 seconds.
step 2 took 1207904003.41 seconds.
step 3 took 1207904003.52 seconds.
step 4 took 1207904003.53 seconds.
step 5 took 1207904003.55 seconds.

Thanks
 
you're referencing $time_start rather than $startTime in your showtime function.

i assume you are using php 5.0.0 or higher. otherwise you need to change your calls from microtime to microtime_float

i also assume that you know that usleep's argument are expressed in microseconds.
 
I completed the code, and I'm gonna share it here with you
Code:
function ShowTime($startTime, $Message)
{
    $time_end = microtime(true);
    $time = $time_end - $startTime;
    echo $Message . " took " . round($time,2) . " seconds.<br/>";
    ob_flush();
    flush();
    return microtime(true);
}

function microtime_float()
{
    list($usec, $sec) = explode(" ", microtime());
    return ((float)$usec + (float)$sec);
}

This is how you should use it, you should first declare a variable at the begining of your code
Code:
$time1 = microtime_float();

Then use it this way everytime you wanna measure elapsed time:
Code:
Action1 codes:
..
..

$time1 = ShowTime($time1,"Action1");

Action2 codes:
..
..
$time1 = ShowTime($time1,"Action2");

It will print
Action 1 took xx.xx seconds
Action 2 took xx.xx seconds

Hope someone finds it useful one day
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top