Mansena
Mansena

Reputation: 31

How to measure total execution time of a function in Linux multithreaded environment

I want to measure the total time spent in a C function within Linux. The function may be called at the same time from different threads, and the times spent should be summed together. How can I do this measurement from Linux? I have looked at the clock() function and to calculate the difference between the start and end of the function.

I found one solution using clock() in this thread within Stackoverflow: How to measure total time spent in a function?

But from what I understand this will also include the CPU processing from threads executes some other function during the time of measurement. Is that a correct assumption?

Is there some other way to do this measurement within Linux?

Upvotes: 2

Views: 2614

Answers (3)

Ctx
Ctx

Reputation: 18410

A very good tool for performance analysis is perf (available with recent linux kernels):

Record performance data with

perf record <command>

and then analyze it with

perf report

Compile your program with debug symbols for useful results.

Upvotes: 1

e.jahandar
e.jahandar

Reputation: 1763

getting time from from clock() and gettimeofday() family functions are good for obtaining precise time difference between two consequent calls, but not good for obtaining time spent in functions, because of thread and process rescheduling of operating system and IO blocking, there isn't any guarantee which your thread/process could obtain CPU until finishes its operations, so you can't relay on time difference. You have two choice for this

  1. Using profiling softwares such as Intel V-Tune and Intel Inspector which will utilize the hardware performance counters

  2. Using Realtime linux kernel, scheduling your process with FIFO scheduler and use time difference, in FIFO scheduler no one interrupt your program so you can safely use the time difference as time spent in functions, using clock(), gettimeofday() or even more precise rdtsc

Upvotes: 0

Sam Varshavchik
Sam Varshavchik

Reputation: 118292

Your question states that you are using Linux.

You can use the getrusage(2) system call with the RUSAGE_THREAD parameter, which will give you the accumulated statistics for the currently running thread.

By comparing what's in ru_utime, and perhaps ru_stime also, before and after your function runs, you should be able to determine how much time the function has accumulated in CPU time, for the currently running thread.

Lather, rinse, repeat, for all threads, and add them up.

Upvotes: 3

Related Questions