php 如何創建uuid


傳統的創建uuid的方法是自己寫個函數實現隨機

<?php
function create_uuid($prefix="") {
    $chars = md5(uniqid(mt_rand(), true));
    $uuid = substr ( $chars, 0, 8 ) . '-'
        . substr ( $chars, 8, 4 ) . '-'
        . substr ( $chars, 12, 4 ) . '-'
        . substr ( $chars, 16, 4 ) . '-'
        . substr ( $chars, 20, 12 );
    return $prefix.$uuid ;
}

$uuid = create_uuid();
var_dump($uuid);

不過現在有擴展了 就使用擴展吧

使用 apt search uuid 搜索一下

sudo apt search uuid

得到結果

然后就安裝吧

使用命令

sudo apt-get install php7.4-uuid

安裝

$ sudo apt-get install php7.4-uuid
Reading package lists... Done
Building dependency tree       
Reading state information... Done
Note, selecting 'php-uuid' instead of 'php7.4-uuid'
The following NEW packages will be installed:
  php-uuid
0 upgraded, 1 newly installed, 0 to remove and 95 not upgraded.
Need to get 8,520 B of archives.
After this operation, 51.2 kB of additional disk space will be used.
Get:1 http://cn.archive.ubuntu.com/ubuntu focal/universe amd64 php-uuid amd64 1.1.0-1build1 [8,520 B]
Fetched 8,520 B in 1s (14.4 kB/s)    
Selecting previously unselected package php-uuid.
(Reading database ... 222525 files and directories currently installed.)
Preparing to unpack .../php-uuid_1.1.0-1build1_amd64.deb ...
Unpacking php-uuid (1.1.0-1build1) ...
Setting up php-uuid (1.1.0-1build1) ...
Processing triggers for libapache2-mod-php7.4 (7.4.3-4ubuntu2.4) ...
Processing triggers for php7.4-cli (7.4.3-4ubuntu2.4) ...

可以看到此時擴展已經有了

$ php -m |grep uuid
uuid

web 端需要 sudo /etc/init.d/apache2 restart 一下

然后 phpinfo()

 之后使用php 函數  uuid_create 即可。

<?php

$uuid = uuid_create(1);
var_dump($uuid);

cli 端得到

string(36) "a84f0c4e-a24b-11eb-87fd-9f2061574580"

web 端得到

經過測試發現還是擴展的方式實現更快。

傳統方式實現uuid 100萬次

代碼

<?php
function create_uuid($prefix="") {
    $chars = md5(uniqid(mt_rand(), true));
    $uuid = substr ( $chars, 0, 8 ) . '-'
        . substr ( $chars, 8, 4 ) . '-'
        . substr ( $chars, 12, 4 ) . '-'
        . substr ( $chars, 16, 4 ) . '-'
        . substr ( $chars, 20, 12 );
    return $prefix.$uuid ;
}

$start_time = microtime(true);
for ($i=0; $i < 1000000; $i++) { 
    $uuid = create_uuid(1);
}
$end_time = microtime(true);
var_dump(($end_time-$start_time));
exit;

效果

 

 擴展實現

<?php
$start_time = microtime(true);
for ($i=0; $i < 1000000; $i++) { 
    $uuid = uuid_create(1);
}
$end_time = microtime(true);
var_dump(($end_time-$start_time));
exit;

效率幾乎提升一倍啊!看來還是擴展厲害啊,畢竟擴展都底層語言了嘛。

不過單次執行一次來看時間幾乎可以忽略不計

傳統方式得到的時間是 4.9829483032227E-5

擴展方式得到的時間是 2.6941299438477E-5

但是單次的這個耗時對比極不穩定,有時候傳統方式用時反而短,這個擴展有時候時間也用的長,這說明單次其實兩者並沒有太大差異。而如果這個東西用到了百次 、萬次循環的時候,它使用擴展就很有用了。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM