-3

コードのミューテックスの開始と終了の時間を測定する必要があるため、次のように記述します。

#include<stdio.h>
#include<string.h>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>
#include<time.h>

pthread_t tid[4];
int counter;
pthread_mutex_t lock;

void* doSomeThing(void *arg)
{
    pthread_mutex_lock(&lock);

    time_t stime=time(NULL);

    unsigned long i = 0;
    counter += 1;
    printf("\n Job %d started\n", counter);

    for(i=0; i<(0xFFFF);i++){
//      printf("%d", i); //this is just wait
    }
    printf("\n Job %d finished\n", counter);

    time_t etime=time(NULL);
    printf("time : %ld\n", difftime(etime, stime));
    pthread_mutex_unlock(&lock);
    return NULL;
}

int main(void)
{
    int i = 0;
    int err;

    if (pthread_mutex_init(&lock, NULL) != 0)
    {
        printf("\n mutex init failed\n");
        return 1;
    }

    while(i < 4)
    {
        err = pthread_create(&(tid[i]), NULL, &doSomeThing, NULL);
        if (err != 0)
            printf("\ncan't create thread :[%s]", strerror(err));
        i++;
    }

    pthread_join(tid[0], NULL);
    pthread_join(tid[1], NULL);
    pthread_join(tid[2], NULL);
    pthread_join(tid[3], NULL);
    pthread_mutex_destroy(&lock);

    return 0;
}

しかし、私が得る時間は0です

4

2 に答える 2

2

タイミングにはさまざまな方法があります。「ウォール タイム」、「CPU 時間」はその 2 つです。タイミング タスクの実行に役立つさまざまなライブラリがあります。ここにいくつかあります:

CPU TIME の場合 (複数の CPU に複数のスレッドがある場合、これは「ウォール クロックよりも高速」になります):

#include <time.h>
clock_t startTime, stopTime;
double msecElapsed;
startTime = clock();
// thing that needs timing
stopTime = clock();
msecElapsed = (stopTime - startTime) * 1000.0 / CLOCKS_PER_SEC;

これは、マイクロ秒の精度でタイミングを取ることができることに注意してください - コンパイラとプラットフォームに依存します。

ELAPSED (壁時計) 時間の場合:

#include <sys/timeb.h>

struct timeb start, stop;
ftime(&start);
// thing that needs timing
ftime(&stop);
msecElapsed = timeDifference(&start, &stop);

次の関数も必要です。

double timeDifference(struct timeb *start, struct timeb *stop) {
  return stop->time - start->time + 0.001 * (stim->millitm - start->millitm);
}

並列処理を容易にするためにOMPを使用している場合、便利な機能があります

#include <omp.h>
double startTime, stopTime;
startTime = omp_get_wtime();
// do things
stopTime = omp_get_wtime();

これは通常、マイクロ秒の精度で計測されます (他の OMP 関数を使用していない場合でも)。

最後に、詳細/提案については、この以前の質問これに対する回答を参照してください。

于 2013-08-29T17:00:49.413 に答える