PHP gzip test

Posted by Tully on Tue 12 October 2010

Today I wrote a quick script to download a web page with both a compressed (gzip) version and a non-compressed version. I wanted something quick that I could run from the command line. The PHP gzip script returns the size of the page in both gzipped and non-gzipped versions. It also calculates the time it took to download each version in seconds. One last feature of the script is that it downloads the page 10 times in both versions, and displays the average of both gzipped and non-gzipped compressed versions.

Usage

php download.php http://example.com

Response

No-Compression:    85047 Time: 0.00 seconds

With-Compression:  11178 Time: 1.00 seconds

Downloading compressed and non-compressed versions 10 times each and
then calculating average...

Non-Compressed version: 0.5

Compressed version: 0.35

Code

function download($site, $gzip=0)
{
    // Headers
    $headers = array('Accept-Encoding: compress, gzip');
    $ch = curl_init($site);

    if ($gzip==1)
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $content = curl_exec($ch);
    return strlen($content);
}

if ($argc < 2) {
    echo "Usage: php $argv[0]\n";
} else {
    $start = time();
    echo "No-Compression:    ".download($argv[1]);
    printf("\tTime: %2.2f seconds \n", number_format(((time() - $start))));
    $start = time();
    echo "With-Compression:  ".download($argv[1], 1);
    printf("\tTime: %2.2f seconds \n", number_format(((time() - $start))));
}

echo "\nDownloading compressed and non-compressed versions\n10 times each and then calculating average... \n";
$times = array();

for ($i=0;$i<20;$i++) {
    $start = time();
    download($argv[1]);
    array_push($times, (time() - $start));
}

echo "Non-Compressed version: ".average($times) . "\n";

$times = array();

for ($i=0;$i<20;$i++) {
    $start = time();
    download($argv[1], 1);
    array_push($times, (time() - $start));
}

echo "Compressed version: ".average($times) . "\n";

// Helper to get average
function average(Array $a)
{
    return array_sum($a) / count($a);
}