Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Measuring CPU time in c++

If I had the following code

clock_t t;
t = clock();
//algorithm
t = clock() - t;

t would equal the number of ticks to run the program. Is this the same is CPU time? Are there any other ways to measure CPU time in C++?

OS -- Debian GNU/Linux I am open to anything that will work. I am wanting to compare the CPU time of two algorithms.

like image 568
user3025872 Avatar asked Nov 23 '13 20:11

user3025872


People also ask

What is clock_t in C?

Description. The C library function clock_t clock(void) returns the number of clock ticks elapsed since the program was launched. To get the number of seconds used by the CPU, you will need to divide by CLOCKS_PER_SEC.

What is CLOCKS_PER_SEC in C?

CLOCKS_PER_SEC is a macro in C language and is defined in the <time.h> header file. It is an expression of type, as shown below: clock_t clock(void) CLOCKS_PER_SEC defines the number of clock ticks per second for a particular machine.

What is CPU execution time?

CPU execution time is the total time a CPU spends computing on a given task. It also excludes time for I/O or running other programs. This is also referred to as simply CPU time.


1 Answers

clock() is specified to measure CPU time however not all implementations do this. In particular Microsoft's implementation in VS does not count additional time when multiple threads are running, or count less time when the program's threads are sleeping/waiting.

Also note that clock() should measure the CPU time used by the entire program, so while CPU time used by multiple threads in //algorithm will be measured, other threads that are not part of //algorithm also get counted.

clock() is the only method specified in the standard to measure CPU time, however there are certainly other, platform specific, methods for measuring CPU time.

std::chrono does not include any clock for measuring CPU time. It only has a clock synchronized to the system time, a clock that advances at a steady rate with respect to real time, and a clock that is 'high resolution' but which does not necessarily measure CPU time.

like image 102
bames53 Avatar answered Sep 22 '22 13:09

bames53