c - 测量 C/C++ 应用程序中总上下文切换的最佳方法是什么?

标签 c linux performance

这是我尝试获取资源使用情况的简单方法,特别是在程序执行过程中发生的总上下文切换。

#include<stdio.h>
#include <sys/resource.h>

int appgetrusage(struct rusage *);
int appgetdiffrusage(struct rusage *, struct rusage *);

int main() {
    struct rusage begin, end;

    appgetrusage(&begin);

/*
* core of the program goes here 
* where lot of system threads are spawned and joined
*
*/

    appgetrusage(&end);
    appgetdiffrusage(&begin, &end);

    return 0;
}


int appgetrusage(struct rusage *usage){
    int who = RUSAGE_SELF;
    struct timeval start, end;
    getrusage(RUSAGE_SELF, usage);
    return 1;
}


int appgetdiffrusage(struct rusage *oldr, struct rusage *newr){

    printf("\n");    
    printf("user time (ms): %llu\n",1000 * ((newr->ru_utime).tv_sec - (oldr->ru_utime).tv_sec) + 
            ((newr->ru_utime).tv_usec - (oldr->ru_utime).tv_usec) / 1000);

    printf("system time (ms): %ld\n", 1000 * ((newr->ru_stime).tv_sec - (oldr->ru_stime).tv_sec) + 
            ((newr->ru_stime).tv_usec - (oldr->ru_stime).tv_usec) / 1000);         

    printf("voluntary context switches : %ld\n", newr->ru_nvcsw - oldr->ru_nvcsw);
    printf("involuntary context switches : %ld\n", newr->ru_nivcsw - oldr->ru_nivcsw);

    return 1;
}
  1. 这是正确的方法吗?
  2. 有人可以提出替代方案吗?或更正? :-)

最佳答案

Can anybody suggest an alternative?

使用性能(https://perf.wiki.kernel.org/index.php/Tutorial#Counting_with_perf_stat):

perf stat your-program

像这样:

>perf stat ./my_test 2
Thread 139828421826304:
Thread 139828411336448:
^[[A./my_test: Terminated

 Performance counter stats for './my_test 2':

      74333.536760 task-clock                #    1.999 CPUs utilized
               627 context-switches          #    0.008 K/sec
                26 cpu-migrations            #    0.000 K/sec
               282 page-faults               #    0.004 K/sec
      182727508914 cycles                    #    2.458 GHz                     [50.00%]
   <not supported> stalled-cycles-frontend
   <not supported> stalled-cycles-backend
      121168605770 instructions              #    0.66  insns per cycle         [75.00%]
       30262379463 branches                  #  407.116 M/sec                   [74.99%]
           1635031 branch-misses             #    0.01% of all branches         [75.01%]

      37.181359478 seconds time elapsed

关于c - 测量 C/C++ 应用程序中总上下文切换的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21847442/

相关文章:

linux - gcov 没有显示任何覆盖率数据

javascript - 选项卡式内容加载速度非常慢

MySQL慢查询日志bug?记录快速查询

c - 使用递归函数编写数学程序

c - 套接字,为什么 ip 以整数格式发送?

c - 使用 AVX 的平铺矩阵乘法

c - 分析 Segmentation fault Core Dump (gdb)

linux - 监控文件变化位置和长度

c - 帮助使此代码针对 SPOJ 运行得更快

c - 在这个例子中我需要考虑字节顺序吗?