Я пытаюсь измерить процессорное время следующего кода - struct timespec time1, time2, temp_time;Почему процессорное время отрицательное
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 вызывается из разных фил следующим образом:
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
Вы значения wrapping: Если t2.tv_sec = t1.tv_sec + 1, но t2.tv_nsec