我需要获得进程/线程时间。我在linux-4.13.4
Ubuntu 16.04
我阅读了一些帖子并获得了
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()
所以我认为如果它是一个单线程程序。不知何故,我可以从sum_exec_runtime
task_struct
的线程运行时间
我添加系统调用以获取时间:
所以我在linux内核中做了一些小改动。
struct task_struct {
...
...
struct sched_entity se;
// TODO: to get start time and end time
u64 start_time;
u64 end_time;
...
...
};
然后,当我致电
时,我将我的系统调用添加到sum_exec_runtime
和start_time
存储end_time
asmlinkage long sys_start_vm_timer(int __user vm_tid);
asmlinkage long sys_end_vm_timer(int __user vm_tid, unsigned long long __user *time);
SYSCALL_DEFINE1(start_vm_timer,
int __user, vm_tid){
(find_task_by_vpid(vm_tid))->vm_start_time =
(find_task_by_vpid(vm_tid))->se.sum_exec_runtime;
return 0;
}
SYSCALL_DEFINE2(end_timer,
int __user, tid,
unsigned long long __user, *time){
u64 vm_time;
(find_task_by_vpid(vm_tid))->vm_end_time =
(find_task_by_vpid(vm_tid))->se.sum_exec_runtime;
printk("-------------------\n");
printk("end_vm_time: vm_elapsed_time = %llu \n", ((find_task_by_vpid(vm_tid))->vm_end_time - (find_task_by_vpid(vm_tid))->vm_start_time) );
vm_time = ((find_task_by_vpid(vm_tid))->vm_end_time - (find_task_by_vpid(vm_tid))->vm_start_time);
copy_to_user(time, &vm_time, sizeof(unsigned long long));
return 0;
}
我用这个程序测试试图获得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;
}
我得到了意想不到的结果。
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
来自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?
答案 0 :(得分:0)
sum_exec_runtime
的值不包括线程的当前运行时。它在需要时更新,而不是连续更新。请参阅update_curr
功能。