php - 当php手册说前者在内部使用后者时,为什么gmmktime()比mktime()更快?

标签 php performance micro-optimization

根据gmmktime() description在 PHP 手册中,它在内部使用 mktime() 。然而,当我运行以下代码时,mktime 循环的运行时间不到 9 秒,而 gmmktime Look 的运行时间不到 2 秒。怎么会这样?

<?php
$count = 1000000;

$startTime = microtime(true);
for ($i = 0; $i < $count; $i++)
{
  mktime();
}
$endTime = microtime(true);
printf("mktime: %.4f seconds\n", $endTime - $startTime);


$startTime = microtime(true);
for ($i = 0; $i < $count; $i++)
{
  gmmktime();
}
$endTime = microtime(true);
printf("gmmktime: %.4f seconds\n", $endTime - $startTime);

输出:

mktime: 8.6714 seconds
gmmktime: 1.6906 seconds

最佳答案

很可能,文档在关于如何实现 gmmktime() 的问题上对您撒了谎 - 它意味着 C 函数 mktime() 正在使用。

如果我们查看实际代码,gmmktime()mktime() 都会传递到内部 php_mktime 函数,该函数需要gmt 参数(对于 gmmktime() 设置为 1)。如果gmt为零,那么它必须做一些额外的工作(//-我添加的注释,其他来自原始代码):

/* Initialize structure with current time */
now = timelib_time_ctor();
if (gmt) {
    timelib_unixtime2gmt(now, (timelib_sll) time(NULL));
} else {
    tzi = get_timezone_info(TSRMLS_C);
    now->tz_info = tzi;
    now->zone_type = TIMELIB_ZONETYPE_ID;
    timelib_unixtime2local(now, (timelib_sll) time(NULL));
}

// ... snip shared code

/* Update the timestamp */
if (gmt) {
    // NOTE: Setting the tzi parameter to NULL skips a lot of work in timelib_update_ts
    // (and do_adjust_timezone)
    timelib_update_ts(now, NULL);
} else {
    timelib_update_ts(now, tzi);
}

/* Support for the deprecated is_dst parameter */
if (dst != -1) {
    php_error_docref(NULL TSRMLS_CC, E_DEPRECATED, "The is_dst parameter is deprecated");
    if (gmt) {
        /* GMT never uses DST */
        if (dst == 1) {
            adjust_seconds = -3600;
        }
    } else {
        /* Figure out is_dst for current TS */
        timelib_time_offset *tmp_offset;
        tmp_offset = timelib_get_time_zone_info(now->sse, tzi);
        if (dst == 1 && tmp_offset->is_dst == 0) {
            adjust_seconds = -3600;
        }
        if (dst == 0 && tmp_offset->is_dst == 1) {
            adjust_seconds = +3600;
        }
        timelib_time_offset_dtor(tmp_offset);
    }
}

我怀疑您可能会发现,每次执行 mktime() 时,它都会重新打开时区描述文件来读取它并获取正确的时区/DST 偏移量。通过使用 gmmktime(),它通过使用 GMT 的内部空时区来跳过这一点 - 因此,速度更快。

关于php - 当php手册说前者在内部使用后者时,为什么gmmktime()比mktime()更快?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7800738/

相关文章:

php - 单击链接时如何使背景变暗?

homebrew - 停止 "php-fpm"( Homebrew 安装)Mac OSX 10.8.2

android - 应用程序仅在 Lollipop 设备上崩溃

android - OpenGL/Android 大 Sprite 四边形表现不佳

c++ - 从简单函数中删除 if 条件

c++ - 使用内部函数提取和移位奇数/偶数位

php - jQuery - 如何在另一个页面中填充一个 div

asp.net - 调整图像大小和性能

performance - 两个看似等效的汇编代码之间的性能差异

javascript - 当表单每行都有不同的名称属性时,PHP 循环数据