Computing CPU time in C++ on Windows

后端 未结 5 952
無奈伤痛
無奈伤痛 2021-02-03 14:50

Is there any way in C++ to calculate how long does it take to run a given program or routine in CPU time?

I work with Visual Studio 2008 running on Wind

5条回答
  •  青春惊慌失措
    2021-02-03 15:14

    Here's one way. It measures routine exeution time in milliseconds.

    clock_t begin=clock(); starts before the route is executed and clock_t end=clock(); starts right after the routine exits.

    The two time sets are then subtracted from each other and the result is a millisecod value.

    #include 
    #include 
    #include 
    using namespace std;
    
    double get_CPU_time_usage(clock_t clock1,clock_t clock2)
    {
        double diffticks=clock1-clock2;
        double diffms=(diffticks*1000)/CLOCKS_PER_SEC;
        return diffms;
    } 
    
    void test_CPU_usage()
    {
      cout << "Standby.. measuring exeution time:  ";
    
      for (int i=0; i<10000;i++)
      {
            cout << "\b\\" << std::flush;
            cout << "\b|" << std::flush;
            cout << "\b/" << std::flush;
            cout << "\b-" << std::flush;
      }
    
      cout << " \n\n";
    }
    
    int main (void)
    {
    
        clock_t begin=clock();
    
        test_CPU_usage();
    
        clock_t end=clock();
    
        cout << "Time elapsed: " << double(get_CPU_time_usage(end,begin)) << " ms ("<

提交回复
热议问题