diff --git a/lectures/optimization/gprof/README.md b/lectures/optimization/gprof/README.md index 067b225..9cfab57 100644 --- a/lectures/optimization/gprof/README.md +++ b/lectures/optimization/gprof/README.md @@ -15,7 +15,7 @@ $ g++ -pg -o test test.cpp ``` ## Example C++ Program -Create a file `test.cpp` with the following code: +Create a file [test.cpp](test.cpp) with the following code: ```cpp #include diff --git a/lectures/optimization/gprof/test.cpp b/lectures/optimization/gprof/test.cpp new file mode 100644 index 0000000..52a54f7 --- /dev/null +++ b/lectures/optimization/gprof/test.cpp @@ -0,0 +1,25 @@ +#include + +void heavyComputation() { + // The use of volatile prevents compiler optimizations that could remove the loops. + volatile long long sum = 0; + for (long long i = 0; i < 500000000; ++i) { + sum += i; // Simple but expensive loop + } +} + +void lightComputation() { + // The use of volatile prevents compiler optimizations that could remove the loops. + volatile int sum = 0; + for (int i = 0; i < 100000; ++i) { + sum += i; // Lighter loop + } +} + +int main() { + heavyComputation(); // Call heavy function once + for (int i = 0; i < 1000; ++i) { + lightComputation(); // Call light function many times + } + return 0; +}