gpt4 book ai didi

c - 如何获取内核中一个线程的运行时间?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:18:40 28 4
gpt4 key购买 nike

我需要获取进程/线程时间。我在 Ubuntu 16.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_struct

中的精确 sum_exec_runtime 获取线程的运行时间

我添加系统调用来获取时间:

所以我在 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_timeend_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呢?

最佳答案

sum_exec_runtime 的值不包括线程的当前运行时间。它在需要时更新,而不是持续更新。请参阅 update_curr 函数。

关于c - 如何获取内核中一个线程的运行时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47130023/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com