John Law
John Law

Reputation: 437

Is microtime() function a reliable way to count time the cpu spent on a whole php-script?

Like there is a simple script which shouldn’t take long, but when the CPU switched to another job mid-script and was doing that job for a while, does it affect the difference between the two calls of microtime() on each end of the small script?

Upvotes: 0

Views: 67

Answers (1)

Wiimm
Wiimm

Reputation: 3517

microtime() returns a value representing the realtime. A possible usage is:

$duration = -microtime(true);
// .... do something .....
$duration += microtime(true);

If you want the CPU usage time, use function rusage()

$ru_start = getrusage();

// .... do something .....

$ru_end = getrusage();
$elapsed_user = $ru_end['ru_utime.tv_sec'] * 1000000
              + $ru_end['ru_utime.tv_usec']
              - $ru_start['ru_utime.tv_sec'] * 1000000
              - $ru_start['ru_utime.tv_usec'];

$elapsed_system = $ru_end['ru_stime.tv_sec'] * 1000000
                + $ru_end['ru_stime.tv_usec']
                - $ru_start['ru_stime.tv_sec'] * 1000000
                - $ru_start['ru_stime.tv_usec'];

Upvotes: 1

Related Questions