【问题标题】:Measure wall clock time before and after a function测量功能前后的挂钟时间
【发布时间】:2023-03-24 12:17:01
【问题描述】:

我正在使用 .当我在 main() 中使用它时它工作得非常好,但不是我尝试使用它的方式。

我正在熟悉 linux 调度程序,并且正在测量不同部分的性能。 我希望能够测量由“线程在就绪队列中花费的总时间”定义的等待时间(它开始执行函数之前的时间)。

我可以很容易地通过在线程函数之前设置一个clock_gettime() 和在函数内部设置另一个来测量这一点。但是我遇到的问题是线程函数内部的时间低于外部的时间,这给了我们一个负时间。

我通过 ubuntu 在我的 Windows 电脑上运行它。

可能是什么问题?

代码:

    clock_gettime(CLOCK_REALTIME,&data.before);
    thread_array[i-1] = data;
    if(pthread_create(&tids[i],&attr,workLoad,(void*) &data) != 0){
                perror("Could not create thread");
                return 1;
            }
        }

    for(int i = 1;i < threadAmount; i++){
            if(pthread_join(tids[i],NULL)!= 0){
                perror("Thread could not wait");
                return 1;
            }
        }

这是我的线程函数:

void *workLoad(void *args) 
{   
    threadData* data = (threadData*) args;
    clock_gettime(CLOCK_REALTIME,&data->after);
    int loopAmount = data->loopAmount;
    int counter = 0;
    for(int i = 0; i < loopAmount; i++){
        counter++;
    }
    return NULL; 
}

时间间隔的结果

【问题讨论】:

  • 尝试使用 CLOCK_MONOTONIC
  • 它带来了相同的结果,负时间@Wazzaps

标签: c linux multithreading time


【解决方案1】:

在以下代码中:

clock_gettime(CLOCK_REALTIME,&data.before);
thread_array[i-1] = data;
if(pthread_create(&tids[i],&attr,workLoad,(void*) &data) != 0){

data 似乎是一个局部变量,您将其地址传递给线程。您还可以将此变量复制到thread_array[i-1]。如果您随后执行thread_array[i-1].after - thread_array[i-1].before,则意味着线程更新了错误的变量。您需要将&amp;thread_array[i-1] 传递给该线程,例如:

if(pthread_create(&tids[i],&attr,workLoad,(void*)&thread_array[i-1]) != 0){

【讨论】:

    猜你喜欢
    • 2013-07-04
    • 1970-01-01
    • 2023-03-03
    • 2013-06-30
    • 1970-01-01
    • 2021-09-30
    • 1970-01-01
    • 1970-01-01
    • 2015-07-25
    相关资源
    最近更新 更多