dimanche 30 juin 2019

Why these results show there is no need to using reserve in vector?

I wrote the code below to measure the time taken to pushback integers 1000k times without using reserve and with reserving. The result was not what I wanted.

All the tests are performed on my Samsung ativtap7 having a core i5 @1.8 Ghz processor, 4 GB RAM and VS2018 C++ Compiler running under Windows 10.

#include <iostream>
#include <vector>
#include "Stopwatch.h"
using namespace std;

int main()
{
    Stopwatch myWatch;
    //pushback 1000k times without reserve
    for (int i = 0; i < 10; i++)
    {
        cout << "try " << i + 1 << endl;
        myWatch.Start();
        vector<int> vec1;
        for (int i = 0; i < 1000000; i++)
        {
            vec1.push_back(i);
        }
        myWatch.End();
        myWatch.LookElapsedTime();

        //pushback 1000k times with reserve
        myWatch.Start();
        vector<int> vec2(1000000);
        for (int i = 0; i < 1000000; i++)
        {
            vec2.push_back(i);
        }

        myWatch.End();
        myWatch.LookElapsedTime();
        cout << endl;
    }
    return 0;
}

I expected results that show the meaningful difference between using reserve and not using reserve but actual results didn't match my expectations.

below is the results.

try 1
1.51118(sec)
1.46981(sec)

try 2 
1.43074(sec)
1.4381(sec)

try 3
1.4428(sec)
1.46196(sec)

try 4
1.41903(sec)
1.43688(sec)

try 5
1.47544(sec)
1.558(sec)

try 6
1.47474(sec)
1.45484(sec)

try 7
1.47731(sec)
1.5908(sec)

try 8
1.77192(sec)
1.72018(sec)

try 9
1.56832(sec)
1.447(sec)

try 10
1.43659(sec)
1.43572(sec)

I want to know why this happened.

Aucun commentaire:

Enregistrer un commentaire