php读取文件夹 phptxt 扫描txt文件效率 对比

zblog1年前zblog问题解答50
# 获取一个 txt 文件中的txt文件数量(一层)
function guiyi_txt_pro_txt_num2($path_txt)
{
    $path_txt = rtrim($path_txt, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; // 确保路径以斜杠结尾
    if (!is_dir($path_txt)) {
        return 0;
    }
    $txt_files = scandir($path_txt);// 一次性读取目录内容
    $txt_files = array_diff($txt_files, ['.', '..']);
    $count = 0;
    foreach ($txt_files as $file) {
        if (strtolower(substr($file, -4)) === '.txt') {
            $count++;
        }
    }
    return $count;
}

# 获取一个 txt 文件中的txt文件数量(一层)
function guiyi_txt_pro_txt_num($path_txt)
{
    $path_txt = rtrim($path_txt, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR; // 确保路径以斜杠结尾
    // 检查路径是否存在且是目录
    if (!is_dir($path_txt)) {
        return 0;
    }
    $txt_files = glob($path_txt . '*.txt', GLOB_NOSORT); // 使用 glob 函数查找 .txt 文件(更高效且简洁)
    return count($txt_files);
}

$path_ceshi = "G:/phpstudy_pro/WWW/www.zblog.cn/zb_users/plugin/guiyi_txt_pro/txt/179955/";
// 使用 scandir
$start = hrtime(true);
for ($i = 0; $i < 100; $i++) {
    guiyi_txt_pro_txt_num2($path_ceshi);
}
$end = hrtime(true);
echo "scandir time: " . ($end - $start) . " seconds MY\n";
$start2 = hrtime(true);
for ($i = 0; $i < 100; $i++) {
    guiyi_txt_pro_txt_num($path_ceshi);
}
$end2 = hrtime(true);
echo "scandir time: " . ($end2 - $start2) . " seconds\n";

win下对比

scandir time: 99460000 seconds MY

scandir time: 3634966000 seconds


linux服务器对比差别不大


虽然 

$txt_files = glob($path_txt . '*.txt', GLOB_NOSORT);

 更简洁 但是 还是 自己循环效率更高

相关文章

array_values 数组的值 使用 array_values 函数获取数组的所有值 array_values 函数返回数组中所有的值,不包含键。

使用 array_values 函数获取数组的所有值array_values 函数返回数组中所有的值,不包含键。...

宝塔mysql重启 service mysql restart

宝塔mysql重启 service mysql restart

service mysql restart...

zblog置顶文章在分类不显示 怎么办?ZC_LISTONTOP_TURNOFF

zblog置顶文章在分类不显示 怎么办?ZC_LISTONTOP_TURNOFF

调整 ZC_LISTONTOP_TURNOFF 选项为true即可。安装 Z-Blog PHP Development Kit 2.6 插件找到 BlogConfig&n...

/www/server/php/80/sbin/php-fpm: error while loading shared libraries: libsodium.so.23: cannot open

/www/server/php/80/sbin/php-fpm: error while loading shared libraries: libsodium.so.23: cannot open

安装php8失败  安装php8.0失败机器的安装源不行 安装源无法安装libsodium-devel软件,所以安装好php后会报错,更换系统的安装源后,重新安装libs...

ZBLOG定义系统常、变量 用户级别 定义文章类型 定义文章状态

<?php /*zb_system/function/c_system_defined.php  * 定义系统常、变量  */ /*  *&...