vector のパフォーマンスを調査するサンプルです。
・Util.h
// パクリ:http://msdn.microsoft.com/ja-jp/library/system.diagnostics.stopwatch(v=vs.80).aspx
class Stopwatch {
private:
unsigned long long frequency_;
unsigned long long elapsed_;
unsigned long long start_;
bool is_running_;
public:
Stopwatch();
void Start();
void Stop();
void Reset();
unsigned long long GetElapsedMilliseconds();
unsigned long long GetElapsedSeconds();
unsigned long long GetElapsedTicks();
unsigned long long GetFrequency();
};
・Util.cc
#include "Util.h"
#include <assert.h>
#include <Windows.h>
Stopwatch::Stopwatch() {
LARGE_INTEGER i;
if(::QueryPerformanceFrequency(&i) == 0) {
assert(false);
}
frequency_ = i.QuadPart;
Reset();
}
void Stopwatch::Start() {
LARGE_INTEGER i;
::QueryPerformanceCounter(&i);
start_ = i.QuadPart;
is_running_ = true;
}
void Stopwatch::Stop() {
if(is_running_) {
LARGE_INTEGER i;
::QueryPerformanceCounter(&i);
elapsed_ += i.QuadPart - start_;
is_running_ = false;
}
}
void Stopwatch::Reset() {
elapsed_ = start_ = 0;
is_running_ = false;
}
unsigned long long Stopwatch::GetElapsedMilliseconds() {
if (is_running_) {
LARGE_INTEGER i;
::QueryPerformanceCounter(&i);
return (elapsed_ + i.QuadPart - start_) * 1000 / frequency_;
} else {
return elapsed_ * 1000 / frequency_;
}
}
unsigned long long Stopwatch::GetElapsedSeconds() {
return GetElapsedTicks() / frequency_;
}
unsigned long long Stopwatch::GetElapsedTicks() {
if (is_running_) {
LARGE_INTEGER i;
::QueryPerformanceCounter(&i);
return elapsed_ + i.QuadPart - start_;
} else {
return elapsed_;
}
}
unsigned long long Stopwatch::GetFrequency()
{
return frequency_;
}
・main.cc
#include "Util.h"
#include <stdio.h>
#include <vector>
#include <iostream>
void main(void)
{
int sum;
Stopwatch sw;
std::vector<int> v(10000);
int a[10000];
int* ha = new int[10000];
sum = 0;
sw.Start();
for(int i = 0; i < 10000; i++) {
v[i] = i * 2;
}
for(int i = 0; i < 10000; i++) {
sum += v.at(i);
}
sw.Stop();
std::cout << "vector=" << sw.GetElapsedTicks() << std::endl;
sum = 0;
//sw.Reset();
sw.Start();
for(int i = 0; i < 10000; i++) {
a[i] = i * 2;
}
for(int i = 0; i < 10000; i++) {
if(0 <= i && i < 10000) {
sum += a[i];
}
}
sw.Stop();
std::cout << "array=" << sw.GetElapsedTicks() << std::endl;
sum = 0;
//sw.Reset();
sw.Start();
for(int i = 0; i < 10000; i++) {
ha[i] = i * 2;
}
for(int i = 0; i < 10000; i++) {
if(0 <= i && i < 10000) {
sum += ha[i];
}
}
sw.Stop();
std::cout << "harray=" << sw.GetElapsedTicks() << std::endl;
std::cout << "freq=" << sw.GetFrequency() << std::endl;
}