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

zblog2年前zblog问题解答128
# 获取一个 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);

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

相关文章

宝塔升级到最新版 python升级 重新执行更新命令,重新安装面板使用的python环境,此操作不会对您的网站、数据库等造成影响,仅仅是针对面板使用的环境修复。

1、将当前Python环境做个备份的操作mv /www/server/panel/pyenv/ /www/backup/pyenv_backup2、重新执行更新命令,重新安装面板使用的python环境...

【zblog各种查】$zbp->GetUploadByID 根据类名表名ID 各种查

查询 表(映射类)    $where = array();     $where[] ...

mysql 优化表 表优化 OPTIMIZE

定期运行数据库维护任务,如  OPTIMIZE TABLE zbp_post ANALYZE TABLE zbp_post ,以保持...

ZBLOG 获取表字段名字

global $zbp;     $fieldID = $zbp->datainfo['Post'][&#...

dechex 函数 ,用于将一个十进制数转换为其对应的十六进制字符串表示。

在PHP中,dechex() 函数是一个内置函数,用于将一个十进制数转换为其对应的十六进制字符串表示。 这个函数在处理数字数据时非常有用,特别是当你需要将数字以十六进制格式输出或存储时。...

/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...