我对C ++来说很新,想要testing一下C ++可以做多less事情:
只需创build一个具有Object-Point(x,y-坐标)的100 Objectc的vector并将其移动到另一个vector。 重复这个k次。 (在这个代码中是1000000次 – int迭代器)。
那么,因为即时通讯非常新的C ++,你看到一个更好的方式来做到这一点,或者我错过了什么?
我在Windows上运行。
#include "Main.h" #include "Point.h" #include <iostream> #include <vector> #include <chrono> int main() { auto start = std::chrono::high_resolution_clock::now(); int Constant = 10; int Iterator = 1000000; std::vector<Point>* tour = new std::vector<Point>(); std::vector<Point>* actions = new std::vector<Point>(); for (int k=0; k<Iterator; k++) { for (int i=0; i<Constant; i++) { for (int j=0; j<Constant; j++) { Point *p = new Point((i * 10) + j,i + 1, j + 1); actions->push_back(*p); } } while(!actions->empty()) { tour->push_back(actions->at(0)); actions->erase(actions->begin()); } actions->clear(); tour->clear(); } auto finish = std::chrono::high_resolution_clock::now(); std::cout << std::chrono::duration_cast<std::chrono::nanoseconds>(finish-start).count() << std::endl; }
考虑在堆栈上分配矢量实例,而不是在堆上,例如:
std::vector<Point>* tour = new std::vector<Point>(); std::vector<Point>* actions = new std::vector<Point>();
只是变成:
// std::vector default constructor creates empty vectors. std::vector<Point> tour; std::vector<Point> actions;
同样,不要不必要地在堆上分配Point
!
Point *p = new Point((i * 10) + j,i + 1, j + 1); actions->push_back(*p);
只要做一些更简单,更高效的事情,比如:
actions.push_back(Point{x, y, z});
而且,你可以使用重载的operator=
从一个向量复制到另一个向量。
destVector = sourceVector;
根据你的附加评论,如果你想从一个向量移动到另一个向量,你可以使用std::move()
,例如:
// Data moved from sourceVector to destVector. // Leaves sourceVector empty. destVector = std::move(sourceVector);
另外,如果你有编译时常量,你可以使用constexpr
:
constexpr int Constant = 10; constexpr int Iterator = 1000000;
我认为你的代码最大的减速是你从一个向量擦除的事实。 当你这样做的时候,每一个元素都会移动到一个位置。 如果你这样做了很多次,你会发现你正在浪费很多处理能力。
所以,而不是复制矢量。
while(!actions->empty()) { tour->push_back(actions->at(0)); actions->erase(actions->begin()); }
变
tour = actions;