[英]Is it possible to check if (and how often) a program was dispatched/scheduled in C under Linux
I would like to know if a program / a thread was dispatched / scheduled in C under Linux and if possible how often. 我想知道一个程序/一个线程是否在Linux下用C调度/调度,如果可能的话,要多久一次。 The reason is that I'm measuring the runtime of a loop and want to prevent false results. 原因是我正在测量循环的运行时间,并希望防止出现错误的结果。
This is a minimal example: 这是一个最小的示例:
#include <stdio.h>
int times_dispatched() {
// how to check?
return 0;
}
int main() {
int i, dummy = 0;
for(i=0; i<10000000; i++) {
dummy++;
}
printf("counted to %d; program was dispatched %d times\n", dummy, times_dispatched());
}
On Linux you can use getrusage function. 在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;
}
Test application: 测试应用:
#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;
}
Output from Ideone : Ideone的输出:
Context switches: 3 voluntarily, 283 involuntarily
PS I wonder why it shows non-zero voluntary switches, may be that is because of using Ideone... On my desktop it is always zero, as expected. PS我不知道为什么它显示非零的自愿开关,可能是因为使用了Ideone ...在我的桌面上,它总是零,如预期的那样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.