0

I have written scripts to download XML data via HTTP. I would like to record (in a database) how long it takes to download the XML file. Does PHP have a built in function for timing the length of a download?

2 Answers 2

3

PHP has built in functions to record time. Many people use microtime() to profile their functions.

Here's an example from the manual:

<?php
$time_start = microtime(1);

// PUT YOUR DOWNLOAD FUNCTION HERE - GWB

$time_end = microtime(1);
$time = $time_end - $time_start;

echo "Downloaded in ".round($time,5)." seconds\n";
?>

IMPORTANT NOTE: As @toon81 mentioned in a comment on the other post, you have to watch out for time changes on the server. As mentioned in the comments section of the microtime manual page

"However it is true that result depends of gettimeofday() call. [...] If system time change, result of this function can be unpredictable (much greater or less than zero)."

11
  • well, the previous comment has been deleted. Two cents on this answer: depending on the function you use to download, the PHP-Script may continue to run (asynchronous download) - so if your times are too low, check the download-function you use.
    – Lars
    Nov 18, 2011 at 9:11
  • This is giving me some metrics. It's different each time. Is this not accurate?
    – Ryan
    Nov 18, 2011 at 9:11
  • my bad. It was me who actually misread the question. I confused upload and download. I apologize for that. Nov 18, 2011 at 9:12
  • @RPM The download times will be different each time. That's just how the Internet works. To get an average download time, you need to record it many times, and average the results. Nov 18, 2011 at 9:14
  • @Col.Shrapnel even with uploading data, your comment would still have been incorrect - anyways, as long as PHP is involved in either down- or upload (and even if just to pipe the file through), you may check the times.
    – Lars
    Nov 18, 2011 at 9:15
1

Make an UNIX timestamp right before and after the download and calculate the difference.

$start = time();
//Download
$end = time();
$time = $end - $start;
//Send to db
2
  • Not sure why your answer got downvoted so much, bro. Seems a perfectly legitimate answer to me. Nov 18, 2011 at 9:08
  • 1
    It's not. First of all, the time function is in seconds and therefore not suitable for profiling functions. Second of all, timing stuff just isn't that simple. Check out the comments here: nl.php.net/manual/en/function.microtime.php
    – toon81
    Nov 18, 2011 at 9:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.