在 C 中计算线程的运行时间



我已经计算了在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("%.4fn", (double)(time(NULL) - start));
    return 0;
}

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

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

喜欢:

pthread_join(thread[0], NULL);
pthread_join(thread[1], NULL);
printf("%.4fn", (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;语句(因为不需要在代码中返回值)。

最新更新