header : <ctime>
or <time.h>
Usage
clock_t
: Arithmetic (until C11)Real (since C11) type capable of representing the processor time used by a process. It has implementation-defined range and precision.
double cpu_time_used = ((double) (end - start))
Example
#include <algorithm>
#include <ctime>
#include <iostream>
int main ()
{
// Generate data
const unsigned arraySize = 32768 ;
int data[arraySize];
for ( unsigned c = 0 ; c < arraySize; ++ c)
data[c] = std :: rand () % 256 ;
// !!! With this, the next loop runs faster.
std :: sort (data, data + arraySize);
// Test
clock_t start = clock ();
long long sum = 0 ;
for ( unsigned i = 0 ; i < 100000 ; ++ i)
{
for ( unsigned c = 0 ; c < arraySize; ++ c)
{ // Primary loop
if (data[c] >= 128 )
sum += data[c];
}
}
double elapsedTime = static_cast<double> ( clock () - start) / CLOCKS_PER_SEC;
std ::cout << elapsedTime << ' \n ' ;
std ::cout << "sum = " << sum << ' \n ' ;
}
C++ Cast