Skip to content

Instantly share code, notes, and snippets.

@bzikarsky
Created November 20, 2014 07:30
Show Gist options
  • Save bzikarsky/26706edc07d5e4cceb05 to your computer and use it in GitHub Desktop.
Save bzikarsky/26706edc07d5e4cceb05 to your computer and use it in GitHub Desktop.
Benchmark session lifetime condition: Mongo vs PHP
<?php
$mongo = new MongoClient();
$db = $mongo->test;
$collection = $db->selectCollection('session');
$sessionCount = $argv[1];
$sampleCount = $argv[2];
$samples = [];
// Setup collection
$collection->drop();
$bulk = [];
for ($i=0; $i<$sessionCount; $i++) {
$data = [
'_id' => "sess_" + $i,
'time' => new MongoDate(time() - rand(0, 3600)),
'data' => new MongoBinData("abc", MongoBinData::BYTE_ARRAY)
];
if (count($samples) < $sampleCount) {
$samples[] = $data;
}
$bulk[] = $data;
if (count($bulk) == 1000) {
$collection->batchInsert($bulk);
$bulk = [];
}
}
$compare = new MongoDate(time() - 1800);
// Benchmark
$t[0] = microtime(true);
for ($i=0; $i<$sampleCount; $i++) {
$doc = $collection->findOne(['_id' => $samples[$i]['_id']]);
if ($doc['time']->sec < $compare->sec) {}
}
$t[1] = microtime(true);
for ($i=0; $i<$sampleCount; $i++) {
$doc = $collection->findOne(['_id' => $samples[$i]['_id'], 'time' => ['$gt' => $compare]]);
}
$t[2] = microtime(true);
// Results
echo 'PHP : ', ($t[1] - $t[0]), "s\n";
echo 'Mongo: ', ($t[2] - $t[1]), "s\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment