0xDEADBEEF

RSS odkazy english edition

pqueue-types.php

class Item {
  public $weight;
  function __construct($weight) { $this->weight = $weight; }
}

function topk($items, $limit) {
  $heap = new \SplPriorityQueue;
  foreach ($items as $item) {
    $heap->insert($item, -$item->weight);
    if ($heap->count() > $limit) $heap->extract();
  }
  return $heap;
}

function measure(string $label, int $limit, int $iters, $gen) {
  $items = iterator_to_array($gen());
  $start = microtime(true);
  for ($i = 0; $i < $iters; $i++) {
    topk($items, $limit);
  }
  echo "$label ", (microtime(true) - $start) * 1000 / $iters, " ms/iter\n";
}


$limit = 25;
$iters = 1000;
mt_srand(1337);

// int
measure("int   ", $limit, $iters, function() {
  for ($i = 0; $i < 20000; $i++) yield new Item(mt_rand());
}) ;

measure("double", $limit, $iters, function() {
  for ($i = 0; $i < 20000; $i++) yield new Item(mt_rand() / mt_getrandmax());
});

// mixed
measure("mixed ", $limit, $iters, function() {
  yield new Item("0");
  for ($i = 0; $i < 20000; $i++) yield new Item(mt_rand() / mt_getrandmax());
});
píše k47 (@kaja47, k47)