Search code examples
c++timeexecution

c++ code execution timer returning 0, need output in milliseconds


I'm trying to figure out how to time the execution of part of my program, but when I use the following code, all I ever get back is 0. I know that can't be right. The code I'm timing recursively implements mergesort of a large array of ints. How do I get the time it takes to execute the program in milliseconds?

//opening input file and storing contents into array
index = inputFileFunction(inputArray);

clock_t time = clock();//start the clock

//this is what needs to be timed
newRecursive.mergeSort(inputArray, 0, index - 1);

//getting the difference        
time = clock() - time;

double ms = double(time) / CLOCKS_PER_SEC * 1000;

std::cout << "\nTime took to execute: " << std::setprecision(9) << ms << std::endl;

Solution

  • You can use the chrono library in C++11. Here's how you can modify your code:

    #include <chrono>
    //...
    auto start = std::chrono::steady_clock::now();
    // do whatever you're timing
    auto end = std::chrono::steady_clock::now();
    auto durationMS = std::chrono::duration_cast<std::chrono::microseconds>(end - start);
    std::cout << "\n Time took " << durationMS.count() << " ms" << std::endl;