我需要估计在同一台计算机的另一个内核上迁移一个 linux 进程需要多少成本。要迁移我使用 sched_setaffinity 系统调用的进程,但我注意到迁移并不总是立即发生,这是我的要求。
更深入地说,我正在创建一个 C 程序,它每次进行两次大量简单计算,第一次没有迁移,第二次有迁移。计算两个时间戳之间的差异应该可以让我粗略估计迁移开销。但是,我需要弄清楚如何迁移当前进程并等到迁移发生
#define _GNU_SOURCE
#define _POSIX_C_SOURCE 199309L
#include <assert.h>
#include <sched.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include <stdint.h>
//Migrates the process
int migrate(pid_t pid) {
const int totCPU = 8;
const int nextCPU = (sched_getcpu() +1) % totCPU;
cpu_set_t target;
CPU_SET(nextCPU, &target);
if(sched_setaffinity(pid, sizeof(target), &target) < 0)
perror("Setaffinity");
return nextCPU;
}
int main(void) {
long i =0;
const long iterations = 4;
uint64_t total_sequential_delays = 0;
uint64_t total_migration_delays = 0;
uint64_t delta_us;
for(int i=0; i < iterations; i++) {
struct timespec start, end;
//Migration benchmark only happens in odd iterations
bool do_migration = i % 2 == 1;
//Start timestamp
clock_gettime(CLOCK_MONOTONIC_RAW, &start);
//Target CPU to migrate
int target;
if(do_migration) {
target = migrate(0);
//if current CPU is not the target CPU
if(target != sched_getcpu()) {
do {
clock_gettime(CLOCK_MONOTONIC_RAW, &end);
}
while(target != sched_getcpu());
}
}
//Simple computation
double k = 5;
for(int j = 1; j <= 9999; j++) {
k *= j / (k-3);
}
//End timestamp
clock_gettime(CLOCK_MONOTONIC_RAW, &end);
//Elapsed time
delta_us = (end.tv_sec - start.tv_sec) * 1000000 + (end.tv_nsec - start.tv_nsec) / 1000;
if(do_migration) total_migration_delays += delta_us;
else total_sequential_delays += delta_us;
}
//Compute the averages
double avg_migration = total_migration_delays / iterations;
double avg_sequential = total_sequential_delays / iterations;
//Print them
printf("\navg_migration=%f, avg_sequential=%f",avg_migration,avg_sequential);
return EXIT_SUCCESS;
}
这里的问题是 do-while 循环(第 46-49 行)有时会永远运行。