测试“file_put_contents”和“fwrite”写入php文件的性能

php 中,我编写了一个示例代码来测量“file_put_contents”和“fwrite”写入文件的性能。

执行时间测试

使用microtime,可以测试处理所花费的时间。

$startTime = microtime(true);

$time = microtime(true) - $startTime; // 处理所用的时间(毫秒)

以下是一个示例代码,通过执行分别使用“file_put_contents”和“fwrite”将相同内容写入“hoge1.txt”和“hoge2.txt”10,000 次的代码来衡量性能。

<?php

// 运行一万次
define('COUNT', 10000);

// 开始测试
$startTime = microtime(true);

for ($i = 0; $i < COUNT; ++$i) {
    file_put_contents('hoge1.txt', 'hogehoge');
}

result($startTime, 'file_put_contents');

// 开始测试
$startTime = microtime(true);

for ($i = 0; $i < COUNT; ++$i) {
    $fp = fopen('hoge2.txt', 'w');    
    fwrite($fp, 'hogehoge');
    fclose($fp);
}

result($startTime, 'fwrite');

function result($time, $str)
{
    echo '测试结果 : ' . $str . '<br>';
    // 显示到少数的第5位
    echo "process time: " . number_format((microtime(true) - $time), 5) . ' 毫秒' . '<br>';
}

测试“file_put_contents”和“fwrite”写入php文件的性能

测试结果

第1次运行:
测试结果 : file_put_contents
process time: 1.99011 毫秒
测试结果 : fwrite
process time: 1.86211 毫秒

第2次运行:
测试结果 : file_put_contents
process time: 1.92111 毫秒
测试结果 : fwrite
process time: 2.10712 毫秒

第3次运行:
测试结果 : file_put_contents
process time: 1.87111 毫秒
测试结果 : fwrite
process time: 2.08412 毫秒

第4次运行:
测试结果 : file_put_contents
process time: 2.05412 毫秒
测试结果 : fwrite
process time: 1.85911 毫秒

第5次运行:
测试结果 : file_put_contents
process time: 1.98511 毫秒
测试结果 : fwrite
process time: 2.10712 毫秒

第6次运行:
测试结果 : file_put_contents
process time: 1.98911 毫秒
测试结果 : fwrite
process time: 2.07812 毫秒

就执行结果而言,“file_put_contents”似乎能好一点点吧。

本文来源:词雅网

本文地址:https://www.ciyawang.com/php-file-put-contents-fwrite.html

本文使用「 署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0) 」许可协议授权,转载或使用请署名并注明出处。

相关推荐