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

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

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

相关文章

set_time_limit(0); // PHP取消脚本最大执行时间限制

set_time_limit(0); // 取消脚本最大执行时间限制...

zblog定义配置信息,在哪个文件?如ShowHint('good')中good是怎么来的?允许哪些,不允许哪些?

zblog定义配置信息,在哪个文件?如ShowHint('good')中good是怎么来的?允许哪些,不允许哪些?

zblog定义配置信息,在哪个文件?如ShowHint('good')中good是怎么来的?允许哪些,不允许哪些?在《zblog的ShowHint()函数,(后台页面顶部)输出函数,z...

php 正则表达式替换 preg_replace 函数

在 PHP 中,你可以使用正则表达式(regular expressions)结合字符串替换函数(如 preg_replace 或 preg_replace_callba...

php 把\u8D8A\u8D70\u8D8A\u5E26\u52B2\ 转为中文 或正常字符

为了将 Unicode 编码转换为正常字符,你可以使用 json_decode 来处理这个字符串,但需要先将它包装成一个有效的 JSON 格式字符串。具体来说,可以将你的字符串放在双引号内,并确保它是...

phpstorm中的正则表达式替换 编辑器IDE

phpstorm中的正则表达式替换 编辑器IDE

phpstorm中的正则表达式替换 编辑器IDE...