未做buffer的程序代码:
1
#include <stdio.h>
2
#include <stdlib.h>
3
#include <sys/types.h>
4
#include <sys/stat.h>
5
#include <string.h>
6
#include <unistd.h>
7
#include <fcntl.h>
8
9
#define CHAR_BUFFER 1
10
#define BUFFER_SIZE 1024
11
#define LINE_BUFFER 128
12
#define MAX_FILE_LINE_NUM 1000000
13
14
int rw_ptr; // read-write pointer
15
int lineNum; // number of lines in the file
16
17
int position_rw_pntr(int fd, int num_lines);
18
char* get_next_line(int fd);
19
int get_next_char(int fd);
20
21
int main(int argc, char *argv[])
22
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
做了buffer的程序代码:
1
#include <stdio.h>
2
#include <stdlib.h>
3
#include <sys/types.h>
4
#include <sys/stat.h>
5
#include <string.h>
6
#include <unistd.h>
7
#include <fcntl.h>
8
9
#define BUFFER_SIZE 1024
10
#define INIT_BUFF_SIZE 64
11
#define INC_BUFF_SIZE 8
12
#define LINE_BUFFER 128
13
#define MAX_FILE_LINE_NUM 1000000
14
15
int rw_ptr; // read-write pointer
16
int lineNum; // number of lines in the file
17
char lineBuf[INIT_BUFF_SIZE];
18
int linePtr;
19
int curBufSize;
20
21
int position_rw_pntr(int fd, int num_lines);
22
char* get_next_line(int fd);
23
int get_next_char(int fd);
24
25
int main(int argc, char *argv[])
26
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
最后用了一个shell脚本来测试两个的运行时间,比较其优劣(其中的BigFile.txt是一个很大的文件):
#!/bin/bash
set `date`
echo start test part1 at $4
../part1/lab2.exe 300000 BigFile.txt > part1.bt
set `date`
echo finish test part1 at $4
set `date`
echo start test part2 at $4
../part2/lab2.exe 300000 BigFile.txt > part2.bt
set `date`
echo finish test part2 at $4
set `date`
echo start test part1 at $4
../part1/lab2.exe 300000 BigFile.txt > part1.bt
set `date`
echo finish test part1 at $4
set `date`
echo start test part2 at $4
../part2/lab2.exe 300000 BigFile.txt > part2.bt
set `date`
echo finish test part2 at $4
用个跑下来,前者要比后者慢一倍。可见buffer的好处。如果调高buffer的size,效果将更明显。