why C clock() returns 0

后端 未结 7 1346
自闭症患者
自闭症患者 2020-11-30 12:48

I\'ve got something like this:

clock_t start, end;
start=clock();

something_else();

end=clock();
printf(\"\\nClock cycles are: %d - %d\\n\",start,end);


        
相关标签:
7条回答
  • 2020-11-30 13:28

    I encountered this same issue while trying to time the difference between a generic class and a non-generic class both using a vector, on Red Hat Linux with C++ and g++ compiler. It appears if your program runs slower than a single clock, the clock() reading will always be zero (0).

    This code will always return 0

    #include <iostream>
    #include <ctime>
    
    using namespace std;
    
    int main() {
    
        cout << clock() << endl;
    
        return 0;
    }
    

    When I added a for loop with an index up to ten million, to slow the program down, then I got a number 20000 as the result from clock()

    #include <iostream>
    #include <ctime>
    
    using namespace std;
    
    int main() {
    
        for (int i = 0; i < 10000000; i++) {}
        cout << clock() << endl;
    
        return 0;
    }
    

    Certainly depending on the stats of your box, the results will vary, I am running this code with multi-processor Xeon CPU's and also a huge amount of RAM.

    0 讨论(0)
提交回复
热议问题