众所周知,php的函数中,有获取当前秒数的time(),也有获取当前微秒数的microtime(),但是并没有获取毫秒数的函数。一般来说都是要我们自己转换的。这边记录一下。
一、获取php毫秒数的代码
/*
* php输入毫秒部分的代码
* */
function msectime() {
list($msec, $sec) = explode(' ', microtime());
$msectime = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
return $msectime;
}
以上代码会直接输出时间戳加毫秒数,格式类似于下面的
1511507346 758
10位的时间戳+3位的毫秒
二、以上代码用到的部分
(1)php的microtime()函数
这个是php获取微妙数的函数,会输出两部分,一部分是微妙数,一部分是当下的时间戳。
具体参考手册:http://www.w3school.com.cn/php/func_date_microtime.asp
(2)php的list()函数
把数组中的值赋给一些变量。
比如:
<?php
$my_array = array("Dog","Cat","Horse");
list($a, $b, $c) = $my_array;
echo "I have several animals, a $a, a $b and a $c.";
//输出结果
I have several animals, a Dog, a Cat and a Horse.
?>
获取毫秒数的代码里面,相当于用list把通过microtime()获取的毫秒数和时间戳赋给了新的变量, m s e c 是 微 秒 部 分 。 msec是微秒部分。 msec是微秒部分。sec是时间戳部分
(3)php的sprintf()自动填充函数
这部分请看我转载的另一篇博客,总结的很好,地址:
http://blog.csdn.net/LJFPHP/article/details/78624821
$msectime = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
//在这句中,'%.0f'中,'%'代表替换符。'f'代表浮点型。'.0'代表小数点位数为0,也就是没有小数点
三、利用获取毫秒的函数测试代码速度:
public function test_iot(Request $request){
//生成10万条数据
$num = 100000;
$device_name = 'ABCD_';
$m = 0;
$strs = '';
//调用获取毫秒时间的函数,t1
$t1 = $this->msectime();
for($i = 0; $i<$num; $i++){
$m = $m+1;
$str=$device_name.str_pad($m,7,'0',STR_PAD_LEFT );
$strs .= '&'.$str;
}
//生成产品编号后,在此获取当前毫秒时间
$t2 = $this->msectime();
$strs = substr($strs,1);
echo'<p>测试str_pad()函数生成100000条的数据</p>';
//两次时间减一下
$t = $t2 - $t1;
echo '<br/>';
print_r($t);
// print_r($strs);
}
结果:
这里的92就代表了执行这段代码,耗费了92毫秒!
end