1

I have the following:

vector<int> vec;

template<class T>
bool Add(const T& t)
{
    auto i = vec.begin();
    while (i != vec.end() && (*i) < t)
        ++i;

    if (i == vec.end())
        vec.push_back(t);
    else
        vec.insert(i, t);
    return true;
}
int main()
{
    clock_t start, finish;
    const int MAX = 100;
    start = clock();
    for (int i = 0; i < MAX; i++)
    {
        int t = rand() % RAND_MAX;
        Add(t);
    }
    finish = clock();

    cout << "Time: " << finish - start << " clicks" << endl;
    cout << "Time: " << (double)(finish - start) / CLOCKS_PER_SEC << " seconds" << endl;

    return 0;
}

I'm trying to measure the amount of time it takes to generate a random number and add it into a vector but my output is:

Time: 0 clicks

Time: 0 seconds

Am I not measuring the lapsed time properly?

Jason
  • 3,777
  • 14
  • 27
pistachiobk
  • 304
  • 2
  • 15
  • 3
    try using std::chrono::steady_clock and making sure that `MAX` is sufficiently large to allow a measurable time-change to occur. – RyanP Aug 19 '15 at 19:19
  • 1
    change your `MAX`: http://rextester.com/ZFBET83938. Now it's very small to see the difference in time with `clock()` – grisha Aug 19 '15 at 19:24
  • Also, don't use rand(), check out the answer to this question for an easy example of a Mersenne Twister implemented in the library as well as a link to why rand() is considered harmful: http://stackoverflow.com/questions/19665818/best-way-to-generate-random-numbers-using-c11-random-library – RyanP Aug 19 '15 at 19:29
  • thank you guys. MAX wasn't big enough to be measurable. I'm taking a look at std::chrono::steady_clock and the library. I didn't know about these alternatives. :) – pistachiobk Aug 19 '15 at 19:34

0 Answers0