PHP内核函数: microtime

Posted by LB on Fri, Feb 22, 2019

microtime

Description

microtime ([ bool $get_as_float = FALSE ] ) : mixed

microtime() returns the current Unix timestamp with microseconds. This function is only available on operating systems that support the gettimeofday() system call.

source file:** /php-src/ext/standard/microtime.c**

Part-1 : 内核抛出定义

1.1 源码

185  /* {{{ proto mixed microtime([bool get_as_float])
286     Returns either a string or a float containing the current time in seconds and microseconds */
387  PHP_FUNCTION(microtime)
488  {
589  	_php_gettimeofday(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0);
690  }
791  /* }}} */

Part-2 : 源码分析

2.1 源码

 149  static void _php_gettimeofday(INTERNAL_FUNCTION_PARAMETERS, int mode)
 250  {
 351  	zend_bool get_as_float = 0;
 452  	struct timeval tp = {0};
 553  
 654  	ZEND_PARSE_PARAMETERS_START(0, 1)
 755  		Z_PARAM_OPTIONAL
 856  		Z_PARAM_BOOL(get_as_float)
 957  	ZEND_PARSE_PARAMETERS_END();
1058  
1159  	if (gettimeofday(&tp, NULL)) {
1260  		RETURN_FALSE;
1361  	}
1462  
1563  	if (get_as_float) {
1664  		RETURN_DOUBLE((double)(tp.tv_sec + tp.tv_usec / MICRO_IN_SEC));
1765  	}
1866  
1967  	if (mode) {
2068  		timelib_time_offset *offset;
2169  
2270  		offset = timelib_get_time_zone_info(tp.tv_sec, get_timezone_info());
2371  
2472  		array_init(return_value);
2573  		add_assoc_long(return_value, "sec", tp.tv_sec);
2674  		add_assoc_long(return_value, "usec", tp.tv_usec);
2775  
2876  		add_assoc_long(return_value, "minuteswest", -offset->offset / SEC_IN_MIN);
2977  		add_assoc_long(return_value, "dsttime", offset->is_dst);
3078  
3179  		timelib_time_offset_dtor(offset);
3280  	} else {
3381  		RETURN_NEW_STR(zend_strpprintf(0, "%.8F %ld", tp.tv_usec / MICRO_IN_SEC, (long)tp.tv_sec));
3482  	}
3583  }
3684  
3785  /* {{{ proto mixed microtime([bool get_as_float])
3886     Returns either a string or a float containing the current time in seconds and microseconds */
3987  PHP_FUNCTION(microtime)
4088  {
4189  	_php_gettimeofday(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0);
4290  }
4391  /* }}} */

2.2 源码详解

首先在87行是Part-1部分提到的PHP引擎对外抛出函数,此处通过PHP_FUNCTION宏定义让PHP引擎拥有过的内核函数microtime .

从49行开始是_php_gettimeofday函数的具体实现函数,具体解析如下:

  1. 54-57行: 从PHP函数调用处解析可选参数get_as_float
  2. 59-61行: 调用操作系统内核函数gettimeofday获取时间信息 (链接)
  3. 63-65行: 如果get_as_float为true则返回double给用户(此处需要注意编译器的bit数量,32和64位精度不一样)
  4. 67-82行: 如果mode为false则构造字符串数据并返回,如果为true则构造数组并返回.

Part-2 : 注意

牵扯到64浮点数据 , 一定要注意编译器的位数 , 精度的不同会造成意想不到的BUG. 你函数能够返回Double类型,要注意.