Skip to content

Instantly share code, notes, and snippets.

@tigercosmos
Last active September 18, 2023 21:42
Show Gist options
  • Save tigercosmos/cf59233a35d0205c0965271b0598e9bb to your computer and use it in GitHub Desktop.
Save tigercosmos/cf59233a35d0205c0965271b0598e9bb to your computer and use it in GitHub Desktop.
/// Make CPUs usage as a sin wave
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <unistd.h>
const float PI = 3.1415926;
const int TIME_SLICE = 40000; // 40 ms
const int PIECE = 500;
const int CYCLE = 10;
int get_time_diff(struct timeval *start, struct timeval *end) {
return 1000000 * (end->tv_sec - start->tv_sec) + end->tv_usec -
start->tv_usec;
}
void run() {
pid_t pid = getpid();
printf("Process ID: %d\n", pid);
struct timeval start;
struct timeval end;
for (int _c = 0; _c < CYCLE; _c++) { // how many cycles
for (int i = 0; i < PIECE; i++) { // a single cycle
int diff = 0;
gettimeofday(&start, NULL);
float ratio = sin(PI * i * 2 / PIECE) * 0.5f + 0.5f;
int run_time = TIME_SLICE * ratio;
while (diff < run_time) {
gettimeofday(&end, NULL);
diff = get_time_diff(&start, &end);
}
usleep(TIME_SLICE - run_time);
}
}
}
int main() {
// create 4 processes for 4 cores
// each process occupies a core
fork(); // 2
fork(); // 4
run();
return 0;
}
@tigercosmos
Copy link
Author

Result:
image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment