-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.c
116 lines (94 loc) · 2.36 KB
/
main.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <time.h>
#include <fcntl.h>
#define READ_BUFFER (2048)
#define FILE_PATH ("test.txt")
int testRead(char* file_path);
int testFread(char* file_path);
int testFreadWithBuffer(char* file_path);
int main()
{
testRead(FILE_PATH);
testFread(FILE_PATH);
testFreadWithBuffer(FILE_PATH);
return 0;
}
int testRead(char* file_path)
{
clock_t begin = clock();
int fd = open(file_path, O_RDONLY);
if(fd < 0)
{
printf("can't read test file %s\n", FILE_PATH);
return errno;
}
char buffer[READ_BUFFER];
int length = sizeof(buffer);
int read_count;
while((read_count = read(fd, buffer, length)) != 0)
{
//printBuffer(buffer, read_count);
}
close(fd);
clock_t end = clock();
double time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
printf("%s\t%lf\n", __func__, time_spent);
}
int testFread(char* file_path)
{
clock_t begin = clock();
FILE* file = fopen(file_path, "r");
if(file == NULL)
{
printf("can't read test file %s\n", FILE_PATH);
return errno;
}
char buffer[READ_BUFFER];
int length = sizeof(buffer);
int read_count;
while((read_count = fread(buffer, 1, length, file)) != 0)
{
// printBuffer(buffer, read_count);
}
fclose(file);
clock_t end = clock();
double time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
printf("%s\t%lf\n", __func__, time_spent);
}
int testFreadWithBuffer(char* file_path)
{
clock_t begin = clock();
FILE* file = fopen(file_path, "r");
if(file == NULL)
{
printf("can't read test file %s\n", FILE_PATH);
return errno;
}
char buffer[READ_BUFFER];
int length = sizeof(buffer);
setvbuf(file, NULL, _IOFBF, READ_BUFFER*4 ); // large buffer
int read_count;
while((read_count = fread(buffer, 1, length, file)) != 0)
{
// printBuffer(buffer, read_count);
}
fclose(file);
clock_t end = clock();
double time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
printf("%s\t%lf\n", __func__, time_spent);
}
void printBuffer(char* buffer, int count)
{
int length = sizeof(buffer);
if(count == length)
{
printf("%s", buffer);
}
else
{
for(int i=0; i< count; i++)
printf("%c", buffer[i]);
}
}