C 如何获取内核中一个线程的运行时?
我需要获得进程/线程时间。我在C 如何获取内核中一个线程的运行时?,c,linux,multithreading,linux-kernel,C,Linux,Multithreading,Linux Kernel,我需要获得进程/线程时间。我在ubuntu16.04中使用linux-4.13.4 我读了一些帖子,明白了 sum_exec_runtime Total time process ran on CPU In real time Nano second units (10^−9) Updated in __update_curr(), called from update_curr() 所以我认为如果它是一个单线程程序。不知何故,我可以通过task\u struct 我添加syscall以获取
ubuntu16.04中使用linux-4.13.4
我读了一些帖子,明白了
sum_exec_runtime
Total time process ran on CPU
In real time
Nano second units (10^−9)
Updated in __update_curr(), called from update_curr()
所以我认为如果它是一个单线程程序。不知何故,我可以通过task\u struct
我添加syscall以获取时间:
所以我在linux内核中做了一些小的改变
struct task_struct {
...
...
struct sched_entity se;
// TODO: to get start time and end time
u64 start_time;
u64 end_time;
...
...
};
然后,当我调用时,我将我的系统调用添加到存储sum\u exec\u runtime
到start\u time
和end\u time
中
asmlong系统启动虚拟机计时器(int用户虚拟机tid)代码>
asmlong-sys\u-end\u-vm\u计时器(int-user-vm\u-tid,unsigned-long-long\u-user*time)代码>
我用这个程序测试,试图得到for循环的时间
#include <stdio.h>
#include <linux/kernel.h>
#include <sys/syscall.h>
#include <unistd.h>
#include <time.h>
#include <sys/time.h>
#include <stdlib.h>
int main(){
int tid = syscall(SYS_gettid);
printf("tid = %d \n", tid);
printf("My process ID : %d\n", getpid());
printf("My parent's ID: %d\n", getppid());
struct timeval start, end;
unsigned long long elapsedTime = 0;
gettimeofday(&start, NULL);
syscall(336, tid);
int i = 0;
int j = 0;
for(i = 0; i < 65535; i++){
j += 1;
}
syscall(337, tid, &elapsedTime);
gettimeofday(&end, NULL);
printf("thread time = %llu microseconds \n", elapsedTime/1000);
printf("gettimeofday = %ld microseconds \n", ((end.tv_sec * 1000000 + end.tv_usec)- (start.tv_sec * 1000000 + start.tv_usec)));
return 0;
}
从dmesg
[63287.065285] tid = 6905
[63287.065288] start_vm_timer = 0
[63287.065701] tid = 6905
[63287.065702] -------------------
[63287.065703] end_vm_timer = 0
[63287.065704] end_vm_time: vm_elapsed_time = 0
我希望它们应该几乎是一样的。但是为什么进程/线程时间为0?sum\u exec\u runtime
的值不包括线程的当前运行时。它会在需要时更新,而不是持续更新。请参阅update\u curr
功能。您确定for
循环没有得到优化吗。1) 它计算从未使用过的结果。2) 它很容易变成i=65535;j=65535
@MFisherKDX我甚至使用gcc-o0 thread\u time thread\u time.c
测试它,并将printf添加到printj
以使用它,仍然sum\u exec\u runtime
是0,我认为它是累积的,包括线程的当前运行时间,如curr->sum\u exec\u runtime+=delta\u exec代码>。
wxf@wxf:/home/wxf/cPrj$ ./thread_time
tid = 6905
My process ID : 6905
My parent's ID: 6595
thread time = 0 microseconds
gettimeofday = 422 microseconds
[63287.065285] tid = 6905
[63287.065288] start_vm_timer = 0
[63287.065701] tid = 6905
[63287.065702] -------------------
[63287.065703] end_vm_timer = 0
[63287.065704] end_vm_time: vm_elapsed_time = 0