C++风格与C风格文件读写效率测试-vs2015,vs2017

 1 void test_write()
 2 {
 3     const int TEST_SIZE = 100000000;
 4     const char* c_plus_write_file = "H://c_plus_write_file.txt";
 5     const char* c_write_file = "g://c_write_file.txt";
 6 
 7     cout << "Test size :" << TEST_SIZE << endl;
 8     //c++ style writing file  
 9     ofstream of(c_plus_write_file);
10     //assert(of);
11     time_t start, end;
12     start = clock();
13     for (int i = 0; i < TEST_SIZE; ++i)
14     {
15         char tmp[1];
16         tmp[0] = char(i);
17         of.write(tmp, 1);
18     }
19     end = clock();
20     of.close();
21     cout << "C++ style: " << end - start << " ms" << endl;
22     //c style writing file  
23     FILE* fp;
24     fopen_s(&fp, c_write_file, "w");
25     start = clock();
26     for (int i = 0; i < TEST_SIZE; ++i)
27     {
28         char tmp[1];
29         tmp[0] = char(i);
30         fwrite(tmp, 1, 1, fp);
31     }
32     end = clock();
33     fclose(fp);
34     cout << "C style: " << end - start << " ms" << endl;
35     cin.get();
36 }
37 
38 //机器配置:
39 //vs2015,vs2017
40 //intel(R)Core(TM)i7-6700HQ CPU@2.6GHZ 2.59GHZ
41 //16.0GB内存 64位操作系统
42 //测试结果:BUF_SIZE越大,C++与C风格时间差越大,数据如下:
43 //BUF_SIZE= 1000: c++平均90ms c平均80ms
44 //BUF_SIZE= 100000000: c++平均70ms c平均30ms
45 //这是读取测试,对于写入操作二者相关则更显著:BUF_SIZE= 100000000: c++平均25秒 c平均20秒
46 void test_read()
47 {
48     const char* read_file = "g://c_write_file.txt";
49     const int BUF_SIZE = 100000000;
50     //char buf[BUF_SIZE];
51     char* buf = new char[BUF_SIZE];
52     time_t start, end;
53 
54     //c style writing file  
55     FILE* fp = fopen(read_file, "rb");
56     assert(fp);
57     start = clock();
58     int len = 0;
59     do
60     {
61         len = fread(buf, 1, BUF_SIZE, fp);
62         //cout<<len<<endl;  
63     } while (len != 0);
64     end = clock();
65     fclose(fp);
66     cout << "C style: " << end - start << " ms" << endl;
67 
68     //c++ style writing file  
69     ifstream ifs(read_file, ios::binary);
70     assert(ifs);
71     start = clock();
72     while (!ifs.eof())
73     {
74         ifs.read(buf, BUF_SIZE);
75     }
76     end = clock();
77     ifs.close();
78     cout << "C++ style: " << end - start << " ms" << endl;
79     
80     delete[] buf;
81     cin.get();
82 }

 

posted @ 2018-02-17 10:59  时空观察者9号  阅读(1366)  评论(0编辑  收藏  举报