How do I call clock()
in C++
?
For example, I want to test how much time a linear search takes to find a given element in an array.
How do I call clock()
in C++
?
For example, I want to test how much time a linear search takes to find a given element in an array.
clock()
returns the number of clock ticks since your program started. There is a related constant, CLOCKS_PER_SEC
, which tells you how many clock ticks occur in one second. Thus, you can test any operation like this:
clock_t startTime = clock();
doSomeOperation();
clock_t endTime = clock();
clock_t clockTicksTaken = endTime - startTime;
double timeInSeconds = clockTicksTaken / (double) CLOCKS_PER_SEC;
#include <iostream>
#include <cstdio>
#include <ctime>
int main() {
std::clock_t start;
double duration;
start = std::clock();
/* Your algorithm here */
duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC;
std::cout<<"printf: "<< duration <<'\n';
}