C
Profiling
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;.
Exercise 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");.
Show example 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;
}
Test yourself
-
Which header defines clock()?
- time.h
- stdio.h
- stdlib.h
- math.h
Show answer
time.h — answer: time.h. clock and CLOCKS_PER_SEC are defined there.
-
busy_work loop
long sum = 0; for (int i = 0; i < ____; i++) sum++;
Show answer
long sum = 0; for (int i = 0; i < n; i++) sum++;
-
Match profiling tools
- clock
- Clock ticks
- gprof
- Call graph
- perf
- Linux profiler
- CLOCKS_PER_SEC
- Second conversion
Next lesson: Cache effects