func.php
3.1 KB
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
<?php
namespace jytools;
//格式化输出
use Swoole\Process;
use Swoole\Event;
function output(): void
{
$args = func_get_args();
$outStr = '[' . timeFormat('ms') . ']:';
foreach ($args as $key => $value) {
$value = is_array($value) ? json_encode($value) : $value;
if (is_bool($value)) {
$value = $value ? 'bool:true' : 'bool:false';
}
$outStr .= count($args) - $key > 1 ? $value . ' ' : $value;
}
echo $outStr . PHP_EOL;
}
//格式化时间
function timeFormat($type = 's', $format = 'Y-m-d H:i:s'): string
{
date_default_timezone_set('Asia/Shanghai');
$microTime = microtime();
list($msTime, $sTime) = explode(' ', $microTime);
$timeStr = date($format, $sTime);
if ($type == 'ms') {
$timeStr .= '.' . sprintf("%03d", floor($msTime * 1000));
}
return $timeStr;
}
// 获取当前时间的微秒数
function getMicrotime(): float|int
{
list($uSec, $sec) = explode(' ', microtime());
return $sec * 1000 + round($uSec * 1000);
}
//获取精度
function getPrecision($number): int
{
$count = 0;
while ($number < 1) {
$number *= 10;
$count += 1;
}
return $count;
}
function getIntervalUnit($interval, $type = 's'): float|int
{
$unitTime = 0;
if ($interval == '1m') {
$unitTime = 60;
}
if ($interval == '5m') {
$unitTime = 60 * 5;
}
if ($interval == '15m') {
$unitTime = 60 * 15;
}
if ($interval == '1h') {
$unitTime = 60 * 60;
}
if ($interval == '4h') {
$unitTime = 60 * 60 * 4;
}
if ($interval == '1d') {
$unitTime = 60 * 60 * 24;
}
return $type == 's' ? $unitTime : $unitTime * 1000;
}
//科学计数法转数字
function scToNum($scStr)
{
$check_str = '';
if (strpos($scStr, 'e') !== false) {
$check_str = 'e';
}
if (strpos($scStr, 'E') !== false) {
$check_str = 'E';
}
if (empty($check_str)) {
return $scStr; //非科学计数直接返回。
}
$num_length = 0;
$split_array = explode($check_str, $scStr);
$num_length += strlen($split_array[0]);
$num_length += (int)str_replace(['-', '+'], '', $split_array[1]);
$float_number = (float)$scStr;
$decimal_string = number_format($float_number, $num_length, '.', '');
$num = rtrim(rtrim($decimal_string, '0'), '.'); //去除小数后多余的0
return $num;
}
//时间戳转ISO8601
function tsToISO($timestamp)
{
$datetime = new \DateTime();
$datetime->setTimestamp(floor($timestamp / 1000));
$datetime->setTimezone(new \DateTimeZone('UTC'));
$milliseconds = sprintf('.%03d', $timestamp % 1000);
return $datetime->format('Y-m-d\TH:i:s') . $milliseconds . 'Z';
}
//以守护进程运行
function runAsDaemon($callback, $isDaemon = true): void
{
if ($isDaemon) {
Process::daemon();
$process = new Process(function () use ($callback) {
call_user_func($callback);
Event::wait();
});
$process->start();
} else {
call_user_func($callback);
Event::wait();
}
}