-3

I am using the gcc compiler for compiling C programs. How can I measure the exact CPU time required by a certain portion of C code or by a particular statement for its execution?

Ry-
  • 218,210
  • 55
  • 464
  • 476
Sanjeev
  • 221
  • 1
  • 4
  • 8

2 Answers2

3

If a crude counter (~20ms resolution) is acceptable, this is my standard hacro:

#include <ctime>
#define CLOCK_TICK(acc, ctr)  ctr = std::clock()
#define CLOCK_TOCK(acc, ctr)  acc += (std::clock() - ctr)
#define CLOCK_RESET(acc) acc = 0
#define CLOCK_REPORT(acc) (1000. * double(acc) / double(CLOCKS_PER_SEC))

static std::clock_t tacc, tctr;

Usage:

CLOCK_TICK(tacc, tctr);
do_something_critical();
CLOCK_TOCK(tacc, tctr);

std::cout << "This took " << CLOCK_REPORT(tacc) << "ms.\n";

In C++11 you can use <chrono> features to get higher-resolution clocks.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • Trouble is, this will give you “wall” time; it’s likely the OP wants CPU time. That will require interfacing with GCC’s profiling system. – J. C. Salomon Nov 17 '11 at 19:26
  • 1
    @jcsalomon: Right, I see. On Linux you can try `getrusage()`, which provides the break-down that you get from the `time` command. – Kerrek SB Nov 17 '11 at 19:31
  • 1
    @jcsalomon: On some systems (e.g., MS VC++) `clock` returns wall time, but when properly implemented: "The clock function returns the implementation’s best approximation to the **processor time** used by the program [...]" (§7.23.2.1/3, emphasis added). – Jerry Coffin Nov 17 '11 at 20:59
1

You want an execution profile of your application. You’ll need to pass the -pg option to GCC when compiling & linking, then run the program through gprof. See this section in Brian J. Gough’s An Introduction to GCC for a short overview of the process.

J. C. Salomon
  • 4,143
  • 2
  • 29
  • 38