#include <iostream>
#include <vector>
#include <time.h>

using namespace std;

typedef unsigned char uchar;

vector<uchar> testVector = { 0, 255, 238, 255 };

vector<vector<uchar>> target_1;
vector<uchar> target_2;
vector<uchar> target_3;
vector<uchar> target_4;

int main()
{
    target_1.reserve(600 * 2000);
    target_2.reserve(600 * 2000 * 4);
    target_3.resize(600 * 2000 * 4, 0);
    target_4.resize(600 * 2000 * 4, 0);

    clock_t start, mid, end, last, theVeryLsat;

    start = clock();
    // 2.6s
    for (int i = 0; i < 600 * 2000; i++)
    {
        target_1.push_back(testVector);
    }

    mid = clock();
    // 12.721s  1 2 對比看出直接push數組快
    for (int i = 0; i < 600 * 2000 * 4; i++)
    {
        for (int i = 0; i < 4; i++)
        {
            target_2.push_back(testVector.at(i));
        }
    }
    end = clock();
    // 3.345s 2 3 對比看出使用迭代器更快
    for (vector<uchar>::iterator p = target_3.begin(); p < target_3.end(); )
    {
        for (int i = 0; i < 4; i++)
        {
            *(p++) = testVector.at(i);
        }
    }
    last = clock();
    // 5.489s 2 4 對比看出事先resize比事先分配內存再push更快
    for (int i = 0; i < 600 * 2000 * 4; i++)
    {
        for (int i = 0; i < 4; i++)
        {
            target_4[i] = testVector.at(i);
        }
    }
    // 最優方法,依次遞減 1. 事先resize,使用數組形式更改數值 2. 使用迭代器訪問 3. reserve後使用push
    theVeryLsat = clock();

    double time_1 = (double)(mid - start) / CLOCKS_PER_SEC;
    double time_2 = (double)(end - mid) / CLOCKS_PER_SEC;
    double time_3 = (double)(last - end) / CLOCKS_PER_SEC;
    double time_4 = (double)(theVeryLsat - last) / CLOCKS_PER_SEC;


    cout << "第一段代碼時間: " << time_1 << "s" << endl;
    cout << "第二段代碼時間: " << time_2 << "s" << endl;
    cout << "第三段代碼時間: " << time_3 << "s" << endl;
    cout << "第四段代碼時間: " << time_4 << "s" << endl;

    return 0;
}

1. resize后直接通过下标访问最快

2. 使用迭代器访问次之

3. reserve后在push比较慢