gpt4 book ai didi

计算C中线程的运行时间

转载 作者:行者123 更新时间:2023-11-30 15:01:06 30 4
gpt4 key购买 nike

我计算了两个函数在main中单独运行时的运行时间。迭代版本花费了17秒,递归版本花费了28秒。现在我正在尝试学习线程。我的想法是创建两个具有不同功能的线程,在调用线程之前启动计时器,然后检查需要多长时间,我的假设是 28 秒直到两个线程退出。但问题是:程序不打印时间,而是打印:“线程开始...线程退出后。

问题:

<强>1。如何修改程序来计算运行时间并希望显示28s

<强>2。我究竟做错了什么?简短解释为什么我的程序无法运行。

#include <stdio.h>
#include <time.h>
#include <unistd.h>
#include <limits.h>
#include <pthread.h>

#define NUMTHREADS 2
pthread_t threads[NUMTHREADS];
int sumArrayRec(int arr[], int size) {
if (size == 1) {
return arr[size - 1];
} else {
return arr[size - 1] + sumArray(arr, size - 1);
}
}

int sumArrayIt(int arr[], int size) {
int sum = 0;
for (int i = 0; i<size; i++) {
sum += arr[i];
}
return sum;
}

void *thread1(void *arg) {
for (int x = 0; x < 999999999; x++) {
sumArrayIt(arg, 10);
}
}

void *thread2(void *arg) {
for (int x = 0; x < 999999999; x++) {
sumArrayRec(arg, 10);
}
}




int main() {
int arr[] = {1,2,3,4,5,6,7,8,9,10};
time_t start = time(NULL);

printf("Threads starting...");
pthread_create(&threads[0], NULL, thread1, arr);
pthread_create(&threads[1], NULL, thread2, arr);


pthread_exit(NULL);
printf("%.4f\n", (double)(time(NULL) - start));

return 0;
}

最佳答案

pthread_exit(NULL) main() 中的调用退出主线程,因此后续的 printf() 根本不会执行。

由于您想要等待线程来计算时间,因此您需要在两个(或您感兴趣的一个线程)上调用pthread_join() in) 线程。

喜欢:

pthread_join(thread[0], NULL);
pthread_join(thread[1], NULL);
printf("%.4f\n", (double)(time(NULL) - start));

执行时间取决于硬件、操作系统调度、系统上运行的其他进程等。因此,您不能期望它是某个方程的函数。

您应该错误检查 pthread_create() 调用:

if (pthread_create(&threads[0], NULL, thread1, arr)) {
printf(stderr, "thread creation error<n");
exit(1);
}

if (pthread_create(&threads[1], NULL, thread2, arr)) {
printf(stderr, "thread creation error<n");
exit(1);
}

此外,根据 Pthreads API 的要求,在线程函数末尾添加 return NULL; 语句(因为您不需要在代码中返回值)。

关于计算C中线程的运行时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41661288/

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