#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include <string.h>
void level1_function(int iterations);
void level2_function(int value);
void level3_function(int value);
void cpu_work(int milliseconds);
void io_work(int milliseconds);
volatile int global_counter = 0;
int main(int argc, char *argv[]) {
int iterations = 10;
if (argc > 1) {
iterations = atoi(argv[1]);
if (iterations <= 0) {
iterations = 10;
}
}
printf("Test program starting with %d iterations\n", iterations);
printf("PID: %d\n", getpid());
level1_function(iterations);
printf("Test completed. Final counter: %d\n", global_counter);
return 0;
}
void level1_function(int iterations) {
printf("Level 1 function entered, will run %d iterations\n", iterations);
for (int i = 0; i < iterations; i++) {
printf("Iteration %d/%d\n", i+1, iterations);
cpu_work(50);
level2_function(i);
io_work(500);
}
printf("Level 1 function completed\n");
}
void level2_function(int value) {
global_counter += value;
cpu_work(100);
level3_function(value * 2);
io_work(200);
}
void level3_function(int value) {
cpu_work(200);
global_counter += value * 3;
io_work(300);
}
void cpu_work(int milliseconds) {
struct timespec start, current;
clock_gettime(CLOCK_MONOTONIC, &start);
int local_counter = 0;
while (1) {
for (int i = 0; i < 10000; i++) {
local_counter += i;
}
clock_gettime(CLOCK_MONOTONIC, ¤t);
long elapsed_ms = (current.tv_sec - start.tv_sec) * 1000 +
(current.tv_nsec - start.tv_nsec) / 1000000;
if (elapsed_ms >= milliseconds) {
break;
}
}
global_counter += local_counter % 100;
}
void io_work(int milliseconds) {
usleep(milliseconds * 1000);
}