Completed
Push — master ( 6c20ac...99f9fc )
by Marcel
01:49
created

Benchmarker::runFor()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 19
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 19
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 14
nc 1
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace UMA\Uuid\Performance;
6
7
use UMA\Uuid\UuidGenerator;
8
9
/**
10
 * Simple test bench to see the approximate
11
 * throughput of a given UuidGenerator.
12
 */
13
class Benchmarker
14
{
15
    /**
16
     * @var UuidGenerator
17
     */
18
    private $benchmarked;
19
20
    public function __construct(UuidGenerator $generator)
21
    {
22
        $this->benchmarked = $generator;
23
    }
24
25
    /**
26
     * Calls $this->benchmarked->generate() continuously
27
     * for the supplied amount of seconds.
28
     *
29
     * Then reports total number of calls and avg throughput.
30
     */
31
    public function runFor(int $runTime)
32
    {
33
        $count = 0;
34
        $threshold = $runTime * 1000000;
35
        $start = self::currentTimeMicros();
36
37
        do {
38
            $count++;
39
            $this->benchmarked->generate('foo');
40
        } while (self::currentTimeMicros() - $start < $threshold);
41
42
        echo \sprintf(
43
            "%s: %s UUIDs in %s seconds (%s op/s)\n",
44
            \get_class($this->benchmarked),
45
            $count,
46
            $runTime,
47
            \number_format($count/$runTime, 1)
48
        );
49
    }
50
51
    private static function currentTimeMicros(): int
52
    {
53
        return (int)(\microtime(true) * 1000000);
54
    }
55
}
56