Write a C program to measure time spent in context switch in Linux OS

后端 未结 6 1388
独厮守ぢ
独厮守ぢ 2020-12-04 07:54

Can we write a c program to find out time spent in context switch in Linux? Could you please share code if you have one? Thanks

6条回答
  •  北荒
    北荒 (楼主)
    2020-12-04 08:07

    Why not just this one as rough estimation?

    #include 
    #include 
    #include 
    #include 
    
    int main(int argc, char **argv) {
            struct timeval tv, tvt;
            int diff;
            gettimeofday(&tv, 0);
            diff = tvt.tv_usec - tv.tv_usec;
            if (fork() != 0) {
                    gettimeofday(&tvt, 0);
                    diff = tvt.tv_usec - tv.tv_usec;
                    printf("%d\n", diff);
            }
            return 0;
    }
    

    Note: Actually we shouldn't put null as the second argument, check man gettimeofday. Also, we should check if tvt.tv_usec > tv.tv_usec! Just a draft.

提交回复
热议问题