Skip to content

Instantly share code, notes, and snippets.

@AndrewTsao
Last active January 27, 2016 13:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AndrewTsao/60bf7a09bf41bbb46648 to your computer and use it in GitHub Desktop.
Save AndrewTsao/60bf7a09bf41bbb46648 to your computer and use it in GitHub Desktop.
STL Vector
#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