Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Timing a for loop with clock

Tags:

c++

Hi so I am trying to do a program that sums 20 consecutive numbers and calculates the time that it took to do so... the problem is that when I run the program the time is always 0... any ideas?

this is what I have so far... thanks!

#include <iostream>
#include <time.h>
using namespace std;

int main()
{
    int finish = 20;
    int start = 1;
    int result = 0;

    double msecs;
    clock_t init, end;

    init = clock();

    for (int i = start; i <= finish; i++)
    {
        result += i;
    }


    end = clock();

    cout << ((float)(end - init)) *1000 / (CLOCKS_PER_SEC);

    system ("PAUSE");

    return 0;
} 
like image 608
denise1633 Avatar asked Jan 25 '26 14:01

denise1633


2 Answers

No matter what technique you use for timing they all have some precision. This simply executes so fast that your timer isn't registering any time as having passed.

Aside #1: Use high_resolution_clock - maybe that will register something non-zero, probably not.

Aside #2: Don't name your variable null, in C++ that implies 0 or a null pointer

like image 96
David Avatar answered Jan 28 '26 02:01

David


You can try this...but you might need version C++11.

This can get down to 0.000001 seconds.

#include <iostream>
#include <ctime>
#include <ratio>
#include <chrono>

//using namespace std;

int main()
{
    using namespace std::chrono;
    high_resolution_clock::time_point t1 = high_resolution_clock::now();

    int finish = 20;
    int start = 1;

    for (int i = start; i <= finish; i++)
    {
        result += i;
    }

    high_resolution_clock::time_point t2 = high_resolution_clock::now();
    duration<double> time_span = duration_cast<duration<double>>(t2 - t1);
    cout << time_span.count() << " seconds" << endl;
    end = clock();

    system ("PAUSE");

    return 0;
}
like image 34
user3437460 Avatar answered Jan 28 '26 03:01

user3437460



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!