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
|
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <chrono>
using namespace std;
string test0(void) {
ifstream infile;
infile.open("foo_40m.txt");
string getlottoline;
while(getline(infile, getlottoline))
{
}
return getlottoline;
}
string test1(void) {
ifstream infile;
infile.open("foo_40m.txt");
vector<string> lotto;
string getlottoline;
while(getline(infile, getlottoline))
{
lotto.push_back(getlottoline);
}
return lotto[10];
}
string test2(void) {
ifstream infile;
infile.open("foo_40m.txt");
vector<string> lotto;
lotto.reserve(50000000);
string getlottoline;
while(getline(infile, getlottoline))
{
lotto.push_back(getlottoline);
}
return lotto[10];
}
int main()
{
typedef string (*fnt)(void);
struct {
string description;
fnt func;
} tests[] = {
{ "Basic read", test0 },
{ "Store in vector", test1 },
{ "Store in reserve vector", test2 },
};
for ( int i = 0 ; i < 3 ; i++ ) {
// Thanks to JLBorges for the timing code
const auto start = std::chrono::steady_clock::now() ;
std::string result = tests[i].func();
const auto end = std::chrono::steady_clock::now() ;
const auto millisecs = std::chrono::duration_cast<std::chrono::milliseconds>(end-start).count();
std::cout << "Test=" << tests[i].description
<< ", Result=" << result
<< ", Time=" << millisecs
<< endl;
}
return 0;
}
$ g++ -std=c++11 proj.cpp
$ ./a.out
Test=Basic read, Result=, Time=1289
Test=Store in vector, Result=Line 10, Time=4677
Test=Store in reserve vector, Result=Line 10, Time=2568
$ ./a.out
Test=Basic read, Result=, Time=1309
Test=Store in vector, Result=Line 10, Time=4682
Test=Store in reserve vector, Result=Line 10, Time=2571
$ ./a.out
Test=Basic read, Result=, Time=1365
Test=Store in vector, Result=Line 10, Time=4669
Test=Store in reserve vector, Result=Line 10, Time=2566
$ g++ -O2 -std=c++11 proj.cpp
$ ./a.out
Test=Basic read, Result=, Time=1111
Test=Store in vector, Result=Line 10, Time=2722
Test=Store in reserve vector, Result=Line 10, Time=1821
$ ./a.out
Test=Basic read, Result=, Time=1176
Test=Store in vector, Result=Line 10, Time=2720
Test=Store in reserve vector, Result=Line 10, Time=1817
$ ./a.out
Test=Basic read, Result=, Time=1162
Test=Store in vector, Result=Line 10, Time=2712
Test=Store in reserve vector, Result=Line 10, Time=1814
|