antonionikolov
antonionikolov

Reputation: 107

How to make g++ to show the execution time in terminal?

I want to make g++ showing me what is the execution time and maybe the return too.

g++ file.cpp -o file
./file

When i make the executable file and then call in it is showing only the output without the return and execution time.

And i want to make it showing something like this:

Process returned 0 (0x0)    execution time : 0.002 s

Thank you for the attention!

Upvotes: 6

Views: 17626

Answers (4)

Read carefully time(7). You may use time(1) externally (from your shell, like answered here). You could also use from inside your program syscalls like clock_gettime(1) etc...

Don't expect timing to be really meaningful or accurate for small delays (e.g. less than half a second).

BTW, your question has not much to do with the GCC compiler (i.e. g++). If using a recent GCC 4.8 with -std=c++11 you could use std::chrono etc etc... And even if using these it is not the compiler which is timing your program (but some library functions using syscalls)

Upvotes: 0

benedek
benedek

Reputation: 396

You can measure how long your process takes with the "time" command.

To determine the return value, you can print the value of the $? environment variable after running your program:

time ./file ; echo Process returned $?

You can also specify how exactly time should format its results with the -f (or --format) option. However, some Linux distributions might use a bash-builtin time implementation by default which lacks that option, so you might have to give the full path to use the real time program:

/usr/bin/time -f "Execution time: %E" ./file

Upvotes: 10

turnt
turnt

Reputation: 3255

Look here first: calculating execution time in c++

You can also use a clock (from time.h)in code (although for multi-threaded code it works kinda funny)

int a;
unsigned t0 = clock(), t1;
std::cin >> a;
t1 = clock() - t0;

Upvotes: 3

Shashwat Kumar
Shashwat Kumar

Reputation: 5297

You can use time command as follows:
time ./file

Upvotes: 9

Related Questions