用C龟etc /的fputc和FREAD / FWRITE之间的速度对比 [英] speed comparison between fgetc/fputc and fread/fwrite in C

查看:258
本文介绍了用C龟etc /的fputc和FREAD / FWRITE之间的速度对比的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,(只是为了好玩),我只是想写一个C code复制一个文件。我读了四周,似乎所有的功能,从流调用读龟etc()(我希望这是真的吗?),所以我用这个函数:

So(just for fun), i was just trying to write a C code to copy a file. I read around and it seems that all the functions to read from a stream call fgetc() (I hope this is this true?), so I used that function:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define FILEr "img1.png"
#define FILEw "img2.png"
main()
{
    clock_t start,diff;
    int msec;
    FILE *fr,*fw;
    fr=fopen(FILEr,"r");
    fw=fopen(FILEw,"w");
    start=clock();
    while((!feof(fr)))
        fputc(fgetc(fr),fw);
    diff=clock()-start;
    msec=diff*1000/CLOCKS_PER_SEC;
    printf("Time taken %d seconds %d milliseconds\n", msec/1000, msec%1000);
    fclose(fr);
    fclose(fw);
}

这给了140毫秒的运行时间<一个href=\"http://www.customity.com/storage/public/image/wallpaper/201007/45-intrepid-ibex-ubuntu-wallpaper-1920x1200-customity.jpeg\"相对=nofollow>在2.10Ghz的Core 2 Duo T6500戴尔Inspiron笔记本电脑这个文件。
然而,当我尝试使用 FREAD / FWRITE ,我得到减少运行时间,我不断增加(字节数即变量被传为每个呼叫ST 在以下code),直到其峰值为10毫秒左右!这里是code:

This gave a run time of 140 ms for this file on a 2.10Ghz core2Duo T6500 Dell inspiron laptop. However, when I try using fread/fwrite, I get decreasing run time as I keep increasing the number of bytes(ie. variable st in the following code) transferred for each call until it peaks at around 10ms! Here is the code:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define FILEr "img1.png"
#define FILEw "img2.png"
main()
{
    clock_t start,diff;
    // number of bytes copied at each step
    size_t st=10000;
    int msec;
    FILE *fr,*fw;
    // placeholder for value that is read
    char *x;
    x=malloc(st);
    fr=fopen(FILEr,"r");
    fw=fopen(FILEw,"w");
    start=clock();
    while(!feof(fr))
     {
        fread(x,1,st,fr);
        fwrite(x,1,st,fw);
     }
    diff=clock()-start;
    msec=diff*1000/CLOCKS_PER_SEC;
    printf("Time taken %d seconds %d milliseconds\n", msec/1000, msec%1000);
    fclose(fr);
    fclose(fw);
    free(x);
}

为什么发生这种情况?即如果 FREAD 实际上是多个调用龟etc 那么为什么速度差?
编辑:是不断增加的字节数规定是指在第二code变量 ST

Why this is happening? I.e if fread is actually multiple calls to fgetc then why the speed difference? specified that "increasing number of bytes" refers to the variable st in the second code

推荐答案

FREAD()并没有叫龟etc()阅读每个字节。

fread() is not calling fgetc() to read each byte.

它的行为的,如果的调用龟etc()反复,但它必须是缓冲直接访问龟etc( )读取,因此它可以更大的数据量直接进行复制。

It behaves as if calling fgetc() repeatedly, but it has direct access to the buffer that fgetc() reads from so it can directly copy a larger quantity of data.

这篇关于用C龟etc /的fputc和FREAD / FWRITE之间的速度对比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆