对比
vector
vector
vector
vector
的时间
结果:
performance是跑20次的平均
-O3
编译:有initializer的两种差不多,另外两种差不多
no initializer
[ave performance] 1916320 us
init to all 0
[ave performance] 1020553 us
init to all -1
[ave performance] 838372 us
init to pos
[ave performance] 1748269 us
无O3:前三种差不多,最后一种时间大概是前三种的1.5倍
no initializer
[ave performance] 3929123 us
init to all 0
[ave performance] 4024427 us
init to all -1
[ave performance] 3152277 us
init to pos
[ave performance] 6734609 us
代码
#include <iostream>
#include <fstream>
#include <vector>
#include <string.h>
#include <chrono>
using namespace std;
typedef chrono::microseconds UnitType;
chrono::_V2::system_clock::time_point t_start, t_end;
UnitType d;
#define TIMING_START t_start = chrono::system_clock::now();
#define TIMING_END(str) \
t_end = chrono::system_clock::now(); \
d = chrono::duration_cast<UnitType>(t_end - t_start); \
cout << str << d.count() << " us" << endl;
void moving_average(double &old_ave, double new_val, int &cnt)
{
++cnt;
double tmp1 = old_ave * ((double(cnt - 1)) / cnt);
double tmp2 = new_val / cnt;
old_ave = tmp1 + tmp2;
}
#define BENCHMARK_INIT(str, ...) \
cout << str << endl; \
ave = 0; \
cnt = 0; \
for (int i = 0; i < repeat_times; ++i) \
{ \
std::cout << "rnd " << i; \
TIMING_START \
__VA_ARGS__ \
TIMING_END(" ") \
absorb_stdout << arr[rand() % sz] << endl; \
moving_average(ave, d.count(), cnt); \
} \
cout << "[ave performance] " << (int64_t)ave << " us" << endl;
#define INIT_TO_POS \
vector<unsigned> arr(sz); \
for (size_t i = 0; i < sz; ++i) \
arr[i] = i;
void compare_init_all_zero_and_other(ostream &absorb_stdout)
{
size_t sz = 1000000000; // 10^9
int repeat_times = 20;
double ave = 0;
int cnt = 0;
BENCHMARK_INIT("no initializer", vector<unsigned> arr(sz);)
BENCHMARK_INIT("\n\ninit to all 0", vector<unsigned> arr(sz, 0);)
BENCHMARK_INIT("\n\ninit to all -1", vector<unsigned> arr(sz, -1u);)
BENCHMARK_INIT("\n\ninit to pos", INIT_TO_POS)
}
int main()
{
ofstream absorb_stdout("tmp.txt");
compare_init_all_zero_and_other(absorb_stdout);
return 0;
}