2014年4月25日 星期五

read,write vs fread, fwrite

The read() and write() are blocking I/O, If your source use the system function read() or write() to access the filesystem that they will actually launch the io system call.

The fread() and fwrite() are user-buffered I/O. The data will keep in the buffer until the data size is filled with the block size then they will launch the real io system call

Experiment with Blocking I/O
write.c
--
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>

int main()
{
    int fd;
    int i;
    char c = 'a';

    fd = open("data.xxx", O_CREAT | O_WRONLY | O_TRUNC);

    for(i = 0; i < 4096; ++i)
        write(fd, &c, 1);

    close(fd);
}

strace -c -e trace=write ./write
% time     seconds  usecs/call     calls    errors syscall
------ ----------- ----------- --------- --------- ----------------
100.00    0.012361           3      4096           write
------ ----------- ----------- --------- --------- ----------------
100.00    0.012361                  4096           total

read.c
--
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>

int main()
{
    int fd;
    int i;
    char c = 'a';

    fd = open("data.xxx",  O_RDONLY);

    while(read(fd, &c, 1));

    close(fd);

}

strace -c -e trace=read ./read
% time     seconds  usecs/call     calls    errors syscall
------ ----------- ----------- --------- --------- ----------------
100.00    0.020256           5      4098           read
------ ----------- ----------- --------- --------- ----------------
100.00    0.020256                  4098           total


User-Buffered IO
fwrite.c
--
#include <stdlib.h>
#include <stdio.h>

int main()
{
    FILE *fp;
    int i;
    char c = 'a';

    fp = fopen("data.xxx", "w");

    for(i = 0; i < 4096; ++i)
        fwrite(&c, 1, 1, fp);

    fclose(fp);
}

strace -c -e trace=write ./fwrite
% time     seconds  usecs/call     calls    errors syscall
------ ----------- ----------- --------- --------- ----------------
100.00    0.000004           4         1           write
------ ----------- ----------- --------- --------- ----------------
100.00    0.000004                     1           total

#include <stdlib.h>
#include <stdio.h>

int main()
{
    FILE *fp;
    int i;
    char c = 'a';

    fp = fopen("data.xxx", "r");

    while(fread(&c, 1, 1, fp));

    fclose(fp);
}

strace -c -e trace=read ./fread
% time     seconds  usecs/call     calls    errors syscall
------ ----------- ----------- --------- --------- ----------------
100.00    0.000009           3         3           read
------ ----------- ----------- --------- --------- ----------------
100.00    0.000009                     3           total

沒有留言:

張貼留言