forked from yitter/IdGenerator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
snowdrift.php
94 lines (76 loc) · 2.46 KB
/
snowdrift.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
<?php
declare(strict_types=1);
namespace SnowDrift;
use FFI;
use FFI\CData;
final class SnowFlake
{
private FFI $ffi;
private CData $flake;
private CData $pflake;
public function __construct(array $config = ['Method' => 1, 'BaseTime' => 0, 'WorkerId' => 1, 'WorkerIdBitLength' => 6, 'SeqBitLength' => 10, 'TopOverCostCount' => 2000])
{
$this->ffi = FFI::cdef(file_get_contents($this->getHeaders()), $this->getLibrary());
$this->flake = $this->ffi->new("struct snowflake");
foreach ($config as $name => $val) {
$this->flake->$name = $val;
}
$this->pflake = FFI::addr($this->flake);
$this->ffi->Config($this->pflake);
}
public function getFFI(): FFI
{
return $this->ffi;
}
public function getFlake(): CData
{
return $this->flake;
}
public function getPflake(): CData
{
return $this->pflake;
}
public function nextId(): int
{
return $this->ffi->NextId($this->pflake);
}
public function getHeaders(): string
{
return __DIR__ . '/src/snowflake/snowflake.h';
}
public function getLibrary(): ?string
{
return __DIR__ . '/src/snowflake/libsnow.so';
}
}
$total = 50000;
$snowflake = new SnowFlake(['Method' => 1, 'BaseTime' => 1577808000000, 'WorkerId' => 1, 'WorkerIdBitLength' => 1, 'SeqBitLength' => 10, 'TopOverCostCount' => 2000]);
$ffi = $snowflake->getFFI();
$pflake = $snowflake->getPflake();
// $res = [];
$start = microtime(true);
for ($i = 0; $i < $total; $i++) {
// $res[] = \SnowDrift::NextId();
\SnowDrift::NextId(2);
}
echo sprintf("扩展漂移算法,PHP循环获取:%d,%s ms", $total, ((microtime(true) - $start)) * 1000) . PHP_EOL;
// $res = [];
$start = microtime(true);
foreach (\SnowDrift::NextNumId($total) as $val) {
// $res[] = $val;
}
echo sprintf("扩展漂移算法,C循环获取:%d,%s ms", $total, ((microtime(true) - $start)) * 1000) . PHP_EOL;
// $res = [];
$start = microtime(true);
for ($i = 0; $i < $total; $i++) {
// $res[] = $ffi->NextId($pflake);
$ffi->NextId($pflake);
}
echo sprintf("FFI漂移算法,PHP循环获取:%d,%s ms", $total, ((microtime(true) - $start)) * 1000) . PHP_EOL;
// $res = [];
$start = microtime(true);
$tmp = $ffi->NextNumId($pflake, $total);
for ($i = 0; $i < $total; $i++) {
// $res[] = $tmp[$i];
}
echo sprintf("FFI漂移算法,C循环获取:%d,%s ms", $total, ((microtime(true) - $start)) * 1000) . PHP_EOL;