0

I have code that generates random numbers from 1-100 and sorts them using the merge sort which I already have in a separate function. Everything works but when I implement clock(); to try and get the running time, I always get zero. I have even tried with larger numbers like 10000 but still, the time passed always gives me zero. here is my code

int main() { clock_t startTime; clock_t endTime; clock_t timePassed; int array[100]; srand(time(NULL)); int n = sizeof(array) / sizeof(array[0]); startTime = clock(); for (int j = 0; j < 100; j++) { array[j] = rand() % 100+1; std::cout << array[j] << " "; } std::cout << "\n"; MergeSort(array, n); std::cout << "After Merge Sort :" << std::endl; PrintArray(array, n); endTime = clock(); timePassed = ((endTime - startTime) / CLOCKS_PER_SEC); std::cout << "\n" << timePassed; } return 0; } 
7
  • Is it giving you 0 or 0.00? could it be that it's rounding? Try cout.precision(9999); Commented Sep 9, 2018 at 4:47
  • try float(timePassed) Commented Sep 9, 2018 at 4:51
  • 6
    the std::chrono faculties of the standard library will give you better and more accurate results. Commented Sep 9, 2018 at 5:12
  • 2
    A bit of terminology: you don't implement clock, you just are using it. clock is implemented inside your C++ or C standard library (on Linux, using clock_gettime(2) ...) Commented Sep 9, 2018 at 5:36
  • May be useful stackoverflow.com/questions/44433440/… Commented Sep 9, 2018 at 8:33

2 Answers 2

1

use

double timePassed = (endTime - startTime) / static_cast<double>(CLOCKS_PER_SEC); 

Plan B for higher accuracy:

#include <iostream> #include <chrono> // ... auto start_time{ std::chrono::high_resolution_clock::now() }; // ... code you want to time auto end_time{ std::chrono::high_resolution_clock::now() }; std::cout << std::chrono::duration_cast<std::chrono::seconds>(end_time - start_time).count() << ":"; std::cout << std::chrono::duration_cast<std::chrono::microseconds>(end_time - start_time).count() << ":"; // ... 
Sign up to request clarification or add additional context in comments.

1 Comment

changing my timepassed type to double and float seems to have given me a number that is not zero. Thank you
0

If you are developing on a Unix system and want to measure the execution time from an application, you can also use the 'time' command like:

time myapplication

see time (Unix) - Wikipedia

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.