zoukankan      html  css  js  c++  java
  • 文件写入速度对比

    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 = "--  测试写入文件末尾注释
    ";
      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("--  测试写入文件末尾注释
    ")
        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
    ", 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,"
    ");
            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
  • 相关阅读:
    vc 定义返回值为字符串函数方法
    typedef用法(二)
    新版.Net开发必备十大工具【转自www.bitsCN.com】
    大公司面试题
    NET(C#)连接各类数据库集锦
    对对象类型和调用方法属性进行存储以提升反射性能
    数据库连接字符串大全
    C#操作注册表的方法
    上班族解除疲劳
    在Microsoft Visual Studio 2005上安装.net3.0开发环境(含开发环境下
  • 原文地址:https://www.cnblogs.com/lizhaoyao/p/14912323.html
Copyright © 2011-2022 走看看