次のコードのCPU時間を測定しようとしています - struct timespec time1、time2、temp_time;なぜCPU時間が負であるか
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &time1);
long diff = 0;
for(int y=0; y<n; y++) {
for(int x=0; x<n; x++) {
float v = 0.0f;
for(int i=0; i<n; i++)
v += a[y * n + i] * b[i * n + x];
c[y * n + x] = v;
}
}
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &time2);
temp_time.tv_sec = time2.tv_sec - time1.tv_sec;
temp_time.tv_nsec = time2.tv_nsec - time1.tv_nsec;
diff = temp_time.tv_sec * 1000000000 + temp_time.tv_nsec;
printf("finished calculations using CPU in %ld ms \n", (double) diff/1000000);
ただし、nの値を大きくすると時間の値は負の値になります。 コードはn = 500の正しい値を出力しますが、n = 700の場合は負の値を出力します 助けていただければ幸いです。ここで
は、完全なコード構造である - 次のように
void run(float A[], float B[], float C[], int nelements){
struct timespec time1, time2, temp_time;
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &time1);
long diff = 0;
for(int y=0; y<nelements; y++) {
for(int x=0; x<nelements; x++) {
float v = 0.0f;
for(int i=0; i<nelements; i++)
v += A[y * nelements + i] * B[i * nelements + x];
C[y * nelements + x] = v;
}
}
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &time2);
temp_time.tv_sec = time2.tv_sec - time1.tv_sec;
temp_time.tv_nsec = time2.tv_nsec - time1.tv_nsec;
diff = temp_time.tv_sec * 1000000000 + temp_time.tv_nsec;
printf("finished calculations using CPU in %ld ms \n"(double) diff/1000000);
}
この関数abovrは異なるFILから呼び出されます。
SIZE = 500;
a = (float*)malloc(SIZE * SIZE * sizeof(float));
b = (float*)malloc(SIZE * SIZE * sizeof(float));
c = (float*)malloc(SIZE * SIZE * sizeof(float));
//initialize a &b
run(&a[SIZE],&b[SIZE],&c[SIZE],SIZE);
あなたの 'a'と' b'アレイは十分に大きいですか?あなたはそれらをあふれさせて、あなたのtime1値を含むランダムなビットのメモリに落書きすることができます。 –
'a []、b []とc []'に適切なメモリを割り当てましたか?ときどき文章が奇妙な問題を引き起こすことがあります。そのような '配列'のために 'std :: vector <>'を使いたいかもしれません。 – Hindol
値はラッピングされています:t2.tv_sec = t1.tv_sec + 1、ただしt2.tv_nsec