Last active
January 27, 2016 13:52
-
-
Save AndrewTsao/60bf7a09bf41bbb46648 to your computer and use it in GitHub Desktop.
STL Vector
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <iomanip> | |
#include <time.h> | |
#include <vector> | |
struct Item { | |
int a; | |
Item(int i): a(i) { | |
std::cout << "ctor" << std::endl; | |
} | |
~Item() { | |
std::cout << "dtor" << std::endl; | |
} | |
Item(const Item& o): a(o.a) { | |
std::cout << "copy ctor" << std::endl; | |
} | |
void operator=(const Item& o) { | |
a = o.a; | |
std::cout << "assign ctor" << std::endl; | |
} | |
}; | |
int main(int argc, char **argv) { | |
int sum = 0; | |
std::vector<Item> items; | |
for (int i = 0; i < 10; i++) | |
items.push_back(Item(i)); | |
clock_t s = clock(); | |
for (int i = 0; i < 10000000; i++) { | |
// 1 第二 | |
for (std::vector<Item>::iterator it = items.begin(), end = items.end(); | |
it != end; | |
++it) | |
sum += it->a; | |
} | |
clock_t e = clock(); | |
std::cout << sum << ";" << (double)(e - s)/CLOCKS_PER_SEC << std::endl; | |
sum = 0; | |
s = clock(); | |
for (int i = 0; i < 10000000; i++) { | |
// 2 最优 在O3 Release下 | |
for (Item *it = &items[0], *end = &items[0] + items.size(); | |
it != end; | |
++it) | |
sum += it->a; | |
} | |
e = clock(); | |
std::cout << sum << ";" << (double)(e - s)/CLOCKS_PER_SEC << std::endl; | |
sum = 0; | |
s = clock(); | |
for (int i = 0; i < 10000000; i++) { | |
// 3 | |
Item* its = &items[0]; | |
for (int i = 0, size = items.size(); i < size; ++i) | |
sum += its[i].a; | |
} | |
e = clock(); | |
std::cout << sum << ";" << (double)(e - s)/CLOCKS_PER_SEC << std::endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment