How to Use Clock() in C++

Using clock() as a timer in c

ISO C says that the "clock function returns the implementation's best approximation to the processor time used by the program since the beginning of an implementation-defined era related only to the program invocation."

In other words, it is not a real-time clock.

On platforms where C code runs as a process that can be put to sleep by an underlying operating system, a proper implementation of clock stops counting when that happens.

ISO C provides a function time that is intended to provide calendar time, encoded as a time_t arithmetic value. The difftime function computes the difference between two time_t values as a floating-point value of type double measuring seconds. On many systems, the precision of time_t is no better than one second, though.

There are POSIX functions for finer resolution time such as gettimeofday, or clock_gettime (with a suitable clock type argument).

How to use clock() in C++

#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';
}

Function clock() in C

clock measures processor time used by your program. Your program does not use processor time while it is sleeping. The rest of your program uses less than a millisecond of time.

To measure “wall clock” or “real world” time, use time, and use difftime to subtract to time_t values, the type returned by time:

#include <stdio.h>
#include <time.h>
#include <unistd.h>

int main(int argc, const char *argv[])
{
time_t before = time(NULL);
sleep(2);
double difference = difftime(time(NULL), before);
printf("The time taken was %g seconds.\n", difference);
}

Execution time of C program

CLOCKS_PER_SEC is a constant which is declared in <time.h>. To get the CPU time used by a task within a C application, use:

clock_t begin = clock();

/* here, do your time-consuming job */

clock_t end = clock();
double time_spent = (double)(end - begin) / CLOCKS_PER_SEC;

Note that this returns the time as a floating point type. This can be more precise than a second (e.g. you measure 4.52 seconds). Precision depends on the architecture; on modern systems you easily get 10ms or lower, but on older Windows machines (from the Win98 era) it was closer to 60ms.

clock() is standard C; it works "everywhere". There are system-specific functions, such as getrusage() on Unix-like systems.

Java's System.currentTimeMillis() does not measure the same thing. It is a "wall clock": it can help you measure how much time it took for the program to execute, but it does not tell you how much CPU time was used. On a multitasking systems (i.e. all of them), these can be widely different.

Accuracy of clock() function in C

The unit of time used by the clock function is arbitrary. On most platforms, it is unrelated to the processor speed. It's more commonly related to the frequency of an external timer interrupt — which may be configured in software — or to a historical value that's been kept for compatibility through years of processor evolution. You need to use the macro CLOCKS_PER_SEC to convert to real time.

printf("Total time taken by CPU: %fs\n", (double)total_t / CLOCKS_PER_SEC);

The C standard library was designed to be implementable on a wide range of hardware, including processors that don't have an internal timer and rely on an external peripheral to tell the time. Many platforms have more precise ways to measure wall clock time than time and more precise ways to measure CPU consumption than clock. For example, on POSIX systems (e.g. Linux and other Unix-like systems), you can use getrusage, which has microsecond precision.

struct timeval start, end;
struct rusage usage;
getrusage(RUSAGE_SELF, &usage);
start = usage.ru_utime;

getrusage(RUSAGE_SELF, &usage);
end = usage.ru_utime;
printf("Total time taken by CPU: %fs\n", (double)(end.tv_sec - start.tv_sec) + (end.tv_usec - start.tv_usec) / 1e-6);

Where available, clock_gettime(CLOCK_THREAD_CPUTIME_ID) or clock_gettime(CLOCK_PROCESS_CPUTIME_ID) may give better precision. It has nanosecond precision.

Note the difference between precision and accuracy: precision is the unit that the values are reported. Accuracy is how close the reported values are to the real values. Unless you are working on a real-time system, there are no hard guarantees as to how long a piece of code takes, including the invocation of the measurement functions themselves.

Some processors have cycle clocks that count processor cycles rather than wall clock time, but this gets very system-specific.

Whenever making benchmarks, beware that what you are measuring is the execution of this particular executable on this particular CPU in these particular circumstances, and the results may or may not generalize to other situations. For example, the empty loop in your question will be optimized away by most compilers unless you turn optimizations off. Measuring the speed of unoptimized code is usually pointless. Even if you add real work in the loop, beware of toy benchmarks: they often don't have the same performance characteristics as real-world code. On modern high-end CPUs such as found in PC and smartphones, benchmarks of CPU-intensive code is often very sensitive to cache effects and the results can depend on what else is running on the system, on the exact CPU model (due to different cache sizes and layouts), on the address at which the code happens to be loaded, etc.

How does the clock function work behind the scene in a multithreading program?

Since the clock function only records the time consumption of each individual CPU that executes the current program. Meaning in a
multi-threaded program, the returned value would be lower than the
wall-clock time.

I can't find a definitive statement in a C Standard but, according to cppreference (which is generally very reliable), your assumption is wrong and the clock() function returns the total (for all CPUs) processor time used by the program (bold emphasis mine):

… For example, if the CPU is shared by other processes, clock
time may advance slower than wall clock. On the other hand, if the
current process is multithreaded and more than one execution core is
available, clock time may advance faster than wall clock.

Using clock() to measure time in C

As Weather Vane said, there are many questions about time measuring in c. Here is one How do I measure time in C?.

Just a comment on your method, you will probably get 0.0s as result if your piece code contains few lines of execution (if you use a modern computer with 4 cpus with a higher frequency, the piece of code will be executed on a few clock cycles).

Using time() and clock() in C Problems

You can calculate the elapsed time using the below formula.

double timeDiff  = (double)(EndTime - StartTime) / CLOCKS_PER_SEC.

Here is the dummy code.

void CalculateTime(clock_t startTime, clock_t endTime)
{
clock_t diffTime = endTime - startTime;
printf("Processor time elapsed = %lf\n", (double)diffTime /CLOCKS_PER_SEC);
}

Hope this helps.

C Programming times and clock functions

Perhaps I just needed to ask the question. I think I just found the answer in The Linux Programming Interface (Kerrisk 2011, pg 206-207). The answer appears to be the the “CPU time” is measured in two different ways.

times returns time measured in “clock ticks.” The number of clock ticks per second can be retrieved using sysconf(_SC_CLK_TCK) and for my system is 100. So each clock tick is about 1/100 of a second.

clock returns time measured in “clocks per second.” Apparently for Unix-compliant systems this should always be 1,000,000. when I print CLOCKS_PER_SEC from the time.h header file, that is what I get on my system.

To get the number of seconds, I must divide the clock return value by 1,000,000, or divide the times return value by 100. This means that for every “clock tick” there are 10,000 “clocks.” That seems to explain the factor of 10,000 difference I saw.

How to use timer in C?

You can use a time_t struct and clock() function from time.h.

Store the start time in a time_t struct by using clock() and check the elapsed time by comparing the difference between stored time and current time.



Related Topics



Leave a reply



Submit