在 Linux 上,您可以使用getrusage函数。
#include <sys/types.h>
#include <sys/time.h>
#include <sys/resource.h>
int times_dispatched(long *vol, long *invol) {
struct rusage usage;
int err;
if ((err = getrusage(RUSAGE_SELF, &usage)) != 0) {
return err;
}
*vol = usage.ru_nvcsw;
*invol = usage.ru_nivcsw;
return 0;
}
测试应用:
#include <stdlib.h>
#include <stdio.h>
#define LOOPS 100000000
static void loop(volatile unsigned int count) {
while(count--) { }
}
int main(void) {
long vol, invol;
loop(LOOPS);
if (times_dispatched(&vol, &invol) != 0) {
fprintf(stderr, "Unable to get dispatch stats");
exit(1);
}
printf("Context switches: %ld voluntarily, %ld involuntarily\n",
vol, invol);
return 0;
}
来自Ideone的输出:
Context switches: 3 voluntarily, 283 involuntarily
PS我想知道为什么它显示非零自愿开关,可能是因为使用了Ideone......在我的桌面上它总是为零,正如预期的那样。