Subversion Repositories php_utils

Rev

Rev 28 | Show entire file | Regard whitespace | Details | Blame | Last modification | View Log | RSS feed

Rev 28 Rev 29
Line 1... Line 1...
1
<?php
1
<?php
2
 
2
 
3
/*
3
/*
4
 * fixed_length_microtime() for PHP
4
 * fixed_length_microtime() for PHP
5
 * Copyright 2022 Daniel Marschall, ViaThinkSoft
5
 * Copyright 2022 Daniel Marschall, ViaThinkSoft
6
 * Version 2022-03-03
6
 * Version 2022-03-08
7
 *
7
 *
8
 * Licensed under the Apache License, Version 2.0 (the "License");
8
 * Licensed under the Apache License, Version 2.0 (the "License");
9
 * you may not use this file except in compliance with the License.
9
 * you may not use this file except in compliance with the License.
10
 * You may obtain a copy of the License at
10
 * You may obtain a copy of the License at
11
 *
11
 *
Line 16... Line 16...
16
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17
 * See the License for the specific language governing permissions and
17
 * See the License for the specific language governing permissions and
18
 * limitations under the License.
18
 * limitations under the License.
19
 */
19
 */
20
 
20
 
21
function fixed_length_microtime() {
21
function fixed_length_microtime($unique=true) {
22
        // This function outputs a fixed-length microtime (can be used for sorting)
22
        // This function outputs a fixed-length microtime (can be used for sorting)
23
        // Additionally, it ensures that the output is always different by waiting 1 microsecond
23
        // Optionally, it ensures that the output is always different by waiting 1 microsecond
24
 
24
 
25
        $ary = explode('.', (string)microtime(true));
25
        $ary = explode('.', (string)microtime(true));
26
        if (!isset($ary[1])) $ary[1] = 0;
26
        if (!isset($ary[1])) $ary[1] = 0;
27
        $ret = $ary[0].'_'.str_pad($ary[1], 4, '0', STR_PAD_RIGHT);
27
        $ret = $ary[0].'_'.str_pad($ary[1], 4, '0', STR_PAD_RIGHT);
28
 
28
 
29
        while (true) {
29
        if ($unique) {
30
                $ary = explode('.', (string)microtime(true));
-
 
31
                if (!isset($ary[1])) $ary[1] = 0;
-
 
32
                $ret2 = $ary[0].'_'.str_pad($ary[1], 4, '0', STR_PAD_RIGHT);
-
 
33
                // Wait until the value changes. This ensures that the microtime will never be the same
-
 
34
                // sleep(0.1) does not work for some reason.
30
                // Make sure value changes by waiting 1 microsecond.
35
                if ($ret != $ret2) break;
31
                usleep(1);
36
        }
32
        }
37
 
33
 
38
        return $ret;
34
        return $ret;
39
}
35
}