Maik
Maik

Reputation: 616

How do I calculate the duration of a calculation in PHP

I have a calculation for primes. And now i want to know how long PHP need for this calculation. I've tooked two microtimes before and after the calculation and substracted it. But the result don't match with my observation. I have to wait over two seconds to get the result, but the calculated result says 0,004 ms. Why is that so and how do I get the real durationtime?

 $prim_arr = array();
 $start = time();

 for ($i = 1; $i <= 20000; $i++) {
   $result = NULL;
   for ($x = 2; $x < $i; $x++) {
     if(!($i % $x)){
       $result = $i;
       break;
     }
   }
     if (!$result) $prim_arr[] = $i;             
 }

 $end = time();
 echo (($end - $start)/1000)." ms";

 print_r($prim_arr);

Upvotes: 1

Views: 429

Answers (4)

Fabrizio D&#39;Ammassa
Fabrizio D&#39;Ammassa

Reputation: 4769

If you need the time in ms, you shouldn't divide by 1000, but multiply.

The time() function returns the value in seconds.

Upvotes: 0

ahmetunal
ahmetunal

Reputation: 3960

time() gives you seconds. Why are you are dividing it into 1000 at the end.

If you want to calculate ms, you should multiply with 1000 or use microtime().

Upvotes: 1

deceze
deceze

Reputation: 522110

time gives you seconds. Try microtime(true) to get actual microseconds as float.

Upvotes: 0

Tatu Ulmanen
Tatu Ulmanen

Reputation: 124778

You are calculating full seconds as time() returns the amount of seconds since unix epoch. Also you cannot divide by 1000 to get the milliseconds, you have to multiply. Use microtime() instead:

$start = microtime(true);

...

$end = microtime(true);
echo ($end - $start).' seconds';
// Or in milliseconds:
echo (($end - $start) * 1000).' ms';

What happened in your example was that you got two times in seconds, eg. 1314173657 and 1314173661. The difference is 4 seconds. You then divided that by 1000 and got 0,004 "milliseconds", which is obviously wrong. Multiplying by 1000 gives the correct result of 4000ms but with poor accuracy. That's where microtime comes in handy.

Upvotes: 7

Related Questions