性能测试(push_back,embrace_back,copy,move)

TL;DR (划到文章末尾)


#include<iostream>
#include<vector>
#include<ostream>
#include<Windows.h>

using namespace std;

class A {
public:
	int a;
	friend ostream& operator <<(ostream& out, A& a);
	A& operator=(int data);
	A(const A& a);
	A(int a);
	A() {}
};

A::A(int a) {
	cout << "new A with " << a << endl;
	this->a = a;
}

A::A(const A& a) {
	cout << "coping" << endl;
	this->a = a.a;
}

A& A::operator=(int data) {
	this->a = data;
	return *this;
}


ostream& operator<<(ostream& out, A& a) {
	out << a.a;
	return out;
}

int main() {

	DWORD t1, t2;
	t1 = GetTickCount();

	vector<A> arr;

	for (int i = 0; i < 10000; i++) {
		A a{ i };
		cout << "before push:" << arr.capacity() << endl;
		arr.push_back(a);
		cout << "after push:" << arr.capacity() << endl;
	}
	cout << "swap begin" << endl;
	iter_swap(arr.begin() + 1, arr.begin());
	cout << "swap end" << endl;
	for (int i = 0; i < 10; i++) {
		cout << arr[i];
	}

	t2 = GetTickCount();
	cout << endl <<  "time = " << ((t2 - t1) * 1.0 / 1000)<<"s" << endl; // seconds

	return 0;
}

结果:

after push:1
new A with 1
before push:1
coping
coping
after push:2
new A with 2
before push:2
coping
coping
coping
after push:3
new A with 3
before push:3
coping
coping
coping
coping
after push:4
new A with 4
before push:4
coping
coping
coping
coping
coping
after push:6
new A with 5
before push:6
coping
after push:6
new A with 6
before push:6
coping
coping
coping
coping
coping
coping
coping
after push:9
new A with 7
before push:9
coping
after push:9
new A with 8
before push:9
coping
after push:9
new A with 9
before push:9
coping
coping
coping
coping
coping
coping
coping
coping
coping
coping
after push:13
new A with 10
before push:13
coping
after push:13
new A with 11
before push:13
coping
after push:13
new A with 12
before push:13
coping
after push:13
new A with 13
before push:13
coping

after push:12138
new A with 9999
before push:12138
coping
after push:12138
swap begin
coping
swap end
1023456789
time = 14.203s

总结:
原程序所花费时间为:14.203s
把push_back改为embrace_back,其他不变,时间为:14.406s;比push_back稍慢。
把push_back(a)改为push_back(move(a)),其他不变,时间为:14.282s;仍然进行了copy
把push_back(a)改为push_back(i),其他不变,时间为:16.859s;
把push_back(a)改为push_back(i),删除A a{ i };其他不变,时间为:14.516s;
把vector arr;改为vector arr(10000);删除A a{ i };arr.push_back(a)改为arr[i] = i;其他不变,时间为9.922s;提升了30%,vector扩容太花时间了

This entry was posted in C++ and tagged . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.