传统的创建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
但是单次的这个耗时对比极不稳定,有时候传统方式用时反而短,这个扩展有时候时间也用的长,这说明单次其实两者并没有太大差异。而如果这个东西用到了百次 、万次循环的时候,它使用扩展就很有用了。