Profiling
- C course
- Advanced
- Lesson 73/83
- 5 min
Learn performance measurement with profiling tools.
Profiling
Profiling measures how much time a program spends in each function. gprof and perf are common tools on Linux; they give call counts and durations for each function.
In this lesson we use the most basic profiling tool: clock(). It is defined in <time.h> and returns processor clock ticks. With clock_t start = clock(); ... clock_t end = clock(); you measure a region. CLOCKS_PER_SEC converts to seconds. In this lesson we only print the loop result so the output stays deterministic.
Measuring time
To measure a function's duration you call clock() before and after. The difference is the elapsed clock ticks; dividing by CLOCKS_PER_SEC gives seconds.
Example: clock_t start = clock(); long r = busy_work(1000000); clock_t end = clock();. In this lesson we only print the loop result instead of the duration; this keeps the output identical across machines. busy_work increments a counter; the compiler may optimize it away. We suppress the unused warning with (void)start; (void)end;.
Practice Profile busy_work
Write long busy_work(int n): long sum = 0; for (int i = 0; i < n; i++) sum++; return sum;. In main add clock_t start = clock();, long r = busy_work(1000000);, clock_t end = clock();. Suppress warnings with (void)start; (void)end;. Print printf("döngü: %ld\n", r); and printf("profiling: hazır\n");.
Starter code
#include <stdio.h>
#include <time.h>
// Write long busy_work(int n): increment counter n times
// main: measure with clock, print result and profiling message
int main(void) {
return 0;
}Sample solution
#include <stdio.h>
#include <time.h>
long busy_work(int n) {
long sum = 0;
for (int i = 0; i < n; i++) sum++;
return sum;
}
int main(void) {
clock_t start = clock();
long r = busy_work(1000000);
clock_t end = clock();
(void)start; (void)end;
printf("döngü: %ld\n", r);
printf("profiling: hazır\n");
return 0;
}Expected output
döngü: 1000000 profiling: hazır
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which header defines clock()?
- time.h Correct answer
- stdio.h
- stdlib.h
- math.h
Explanation: answer: time.h. clock and CLOCKS_PER_SEC are defined there.
2 busy_work loop
long sum = 0; for (int i = 0; i < ____; i++) sum++;
long sum = 0; for (int i = 0; i < n; i++) sum++;
Explanation: The loop runs n times and sum becomes n.
3 Match profiling tools
| Term | Meaning |
|---|---|
clock |
Clock ticks |
gprof |
Call graph |
perf |
Linux profiler |
CLOCKS_PER_SEC |
Second conversion |