C/C++ Examples¶
Basic C Measurement¶
Given algorithm.c:
#include <stdio.h>
#include <math.h>
double compute(int n) {
double sum = 0.0;
for (int i = 0; i < n; i++)
sum += sin(i) * cos(i);
return sum;
}
int main() {
double result = compute(10000000);
printf("Result: %f\n", result);
return 0;
}
Measure energy:
# Coarse: total program energy
codegreen measure c algorithm.c --
# Fine: per-function breakdown
codegreen measure c algorithm.c -g fine
CodeGreen automatically compiles with -O2 and links against libcodegreen-nemb.so.
C++ Measurement¶
Given nbody.cpp:
codegreen measure cpp nbody.cpp -- 5000
codegreen measure cpp nbody.cpp -g fine --export-plot energy.html -- 5000
How It Works for C/C++¶
- Tree-sitter parses the source and identifies function definitions
- Checkpoint calls are injected at function enter/exit points
- The instrumented source is compiled with
gcc/g++, linking-lcodegreen-nemb -lpthread - The compiled binary runs with
LD_LIBRARY_PATHset to findlibcodegreen-nemb.so - Results are collected via the same NEMB backend as Python
Notes¶
- C++ class bodies are not instrumented (executable statements cannot be placed there)
- Compilation flags:
-O2by default for realistic energy measurement - The
-lpthreadflag is required for the NEMB background polling thread