Simple for() loop benchmark takes the same time with any loop bound

后端 未结 5 1574
有刺的猬
有刺的猬 2020-12-11 19:50

I\'m willing to write a code that makes my CPU execute some operations and see how much time does he take to solve them. I wanted to make a loop going from i=0 to i<5000

5条回答
  •  情书的邮戳
    2020-12-11 20:28

    I slightly altered your code to be the following:

    #include 
    #include 
    
    using namespace std;
    
    int main() {
        for (long long int j = 10000000; j <= 10000000000; j = j * 10) {
    
            int start_s = clock();
    
            for (long long int i = 0; i < j; i++) {
                i * 434243;
            }
    
            int stop_s = clock();
    
            cout << "time: " << (stop_s - start_s) / double(CLOCKS_PER_SEC) * 1000 << endl;
        }
    
        int k;
        cin >> k;
        return 0;
    }
    

    Output: (Which looks perfectly fine to me.)

    time: 23
    time: 224
    time: 2497
    time: 21697
    

    There is one thing to be aware of. Since i is an integer, it never will be equal to 49058349083 anyways. In your case upper bound is converted to int which corresponds to anything between -2,147,483,648 and 2,147,483,647 so loop runs anything between 0 and 2,147,483,647 times which is not that big of a number for a simple multiplication operation. (1813708827 in case of 49058349083).

    Try using long long int which can be between -2^63 and 2^63-1

提交回复
热议问题