文件写入速度对比

php 打开并写入文件 10万次

复制代码
<?php
$start_time = microtime(true);

for ($i=0; $i < 100000; $i++) { 
  $myfile = fopen("php_log.txt", "w") or die("Unable to open file!");
  $txt = "--  测试写入文件末尾注释\n";
  fwrite($myfile, $txt);
  fclose($myfile);
}

$end_time = microtime(true);
var_dump(($end_time-$start_time)*1000);
复制代码

耗时 6955.2180767059 毫秒 即 接近 7 秒

换成 file_put_contents 试试

耗时 7004.5571327209 毫秒 即 7 秒多一点

那说明其实这两种写法差异不大。

采用lua语言试试 由于10万次写入时间太短,改为100万次统计方便点

复制代码
print(os.time() .. "---"..os.clock())

for i=1,1000000 do
    file = io.open("lua_log.txt", "a")
    io.output(file)
    io.write("--  测试写入文件末尾注释\n")
    io.close(file)
end

print(os.time() .. "---"..os.clock())
复制代码

打印结果如下:

1624246878---0.00437
1624246884---6.618569

耗时 6.6 秒 ,但是这是100万次哦,所以结果要处以10, 即 660 毫秒,也就是 0.66 秒

然后发现lua的速度是php的10倍左右

然后试试C语言呢

复制代码
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/time.h>

int write_file_now(char *str);

int main(int argc, char *argv[])
{
    struct timeval tvafter,tvpre;
    struct timezone tz;

    gettimeofday (&tvpre , &tz);

    long msecond_diff = 0;
    char *write_str = "--  测试写入文件末尾注释";
    write_file_now(write_str);

    gettimeofday (&tvafter , &tz);

    msecond_diff = (tvafter.tv_sec-tvpre.tv_sec)*1000+(tvafter.tv_usec-tvpre.tv_usec)/1000; 
    printf("%ld\n", msecond_diff);
    
    return EXIT_SUCCESS;
}
int write_file_now(char *str)
{
    FILE *fp = NULL;
    for(int i = 0;i < 100000; i++)
    {
        fp = fopen("./c_log.txt", "w+");
        fputs(str, fp);
        fprintf(fp,"\n");
        fclose(fp);
    }
    return 1;
}
复制代码

耗时 7536 毫秒,也就是 7.536 秒

这样的话我们大概算一下统计

10万次写入 耗时(毫秒)
php fopen fwrite 6955
php file_put_contents 7004
lua 660
c 7536

但是如果把这种打开写入再关闭换为 打开 -> 循环10万次写入 -> 再关闭 则 c语言效率最高,基本上1千万条写入耗时0.5秒。

先打开文件然后循环10万次写入再关闭 耗时(毫秒)
php fopen fwrite 151
lua 13
c 4

下面是整理的具体对比

语言 循环打开写入关闭10万次(毫秒) 打开连续循环写入再关闭10万次(毫秒) 打开循环连续写入再关闭1000万次(毫秒)
c 7285 4 415
lua 823 13 1000
perl 7630 13 1008
rust 6679 138 12740
php 7758 151 18856
c++ 6647 231 19000
posted @   李照耀  阅读(490)  评论(0编辑  收藏  举报
编辑推荐:
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
阅读排行:
· 在鹅厂做java开发是什么体验
· 百万级群聊的设计实践
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
历史上的今天:
2017-06-21 jquery书写左右两个多选下拉列表交换移除功能
点击右上角即可分享
微信分享提示