Skip to content

Instantly share code, notes, and snippets.

@tony4d
Created January 21, 2013 20:36
Show Gist options
  • Save tony4d/4589094 to your computer and use it in GitHub Desktop.
Save tony4d/4589094 to your computer and use it in GitHub Desktop.
Benchmark the memcache php extension from cli
<?php
/*
exit codes:
0 - everything ok.
1 - failure to connect
*/
if ( ! extension_loaded('memcache') ) {
die("memcache pecl module is not available. Please install a STABLE version from http://pecl.php.net/package/memcache");
}
switch ( $_SERVER['argc'] ) {
case 2:
list($command, $host) = $_SERVER['argv'];
$port = 11211;
break;
case 3:
list($command, $host, $port) = $_SERVER['argv'];
break;
case 4:
list($command, $host, $port, $chunk_size) = $_SERVER['argv'];
break;
default:
list($command) = $_SERVER['argv'];
echo "Arguments: $command hostname [port] [chunk_size]\n";
exit(1);
}
if ($port === null) $port = 11211; // default memcache port is 11211
if ($chunk_size === null) $chunk_size = 8192; // default php memcache chunk size is 8192
$stdout = fopen('php://stdout','wt');
$stderr = fopen('php://stderr','wt');
// Make sure we can connect
$mem = memcache_connect($host, $port);
if ( $mem === false ) {
fprintf($stderr,"Memcache: Failed to connect to %s:%d\n", $host, $port);
exit(1);
}
memcache_close($mem);
// performance test
ini_set('memcache.chunk_size', $chunk_size);
$obj = new Memcache();
$obj->addServer($host, $port);
$tests = 1000;
testObj($obj, $tests);
fclose($stdout);
fclose($stderr);
function testObj($obj, $tests)
{
$key = 'my_testing_key_memcache_test';
printf("%d sets and gets will be performed for each object size\n", $tests);
echo "Times shown are the average to set or get 1 object at given size\n";
for ($size = 1; $size < 20; $size+=2)
{
$results = array();
$bytes = $size * 1024;
$data = str_repeat('1', $bytes);
$size_format = "$size";
if ($size < 10)
{
$size_format = " $size_format";
}
printf("%s KB Objects :: ", $size_format);
$start = microtime(true);
for ($i = 0; $i < $tests; $i++)
{
$obj->set($key.$i, $data, 0, 15);
}
$time = microtime(true) - $start;
$micro = ($time / $tests) * 1000000;
$speed = number_format($micro, 3);
printf("Set: %s microseconds | ", $speed);
$start = microtime(true);
for ($i = 0; $i < $tests; $i++)
{
$obj->get($key.$i);
}
$time = microtime(true) - $start;
$micro = ($time / $tests) * 1000000;
$speed =number_format($micro, 3);
printf("Get: %s microseconds\n", $speed);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment