lolly pop
lolly pop

Reputation: 57

Calculating the total time for which program ran in c

I have a program in c which runs forever until I press CTRL+C. After the termination I need to show the total time for which the program ran. What to do so as to find the total time for which the program ran? if there is a code for it then please let me know. Thanks

Upvotes: 4

Views: 135

Answers (2)

You can use times(2) (or clock_gettime(2) with CLOCK_PROCESS_CPUTIME_ID), or simply clock(3), to get the processor time (inside your program in C).

If you need the real elapsed time, record the start time using time(2) or preferably clock_gettime(2) and compute the difference at end. You might want to get a double measurement of time using this to convert what clock_gettime gives you (a struct timespec) into a double.

Read also time(7) (and signal(7) if you want to catch Ctrl-C, see also tty(4)). Perhaps using time(1) -as suggested by Grzegorz Żur- should be enough.

You should read Advanced Linux Programming & intro(2) & syscalls(2).

Upvotes: 3

Grzegorz Żur
Grzegorz Żur

Reputation: 49161

Yes, there is a program called time.

Run

time ./program

Upvotes: 4

Related Questions