C语言 gcc: CLOCK_REALTIME is undeclared



我试图运行我在这个网站上找到的C代码

#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#define n 2048
double A[n][n];
double B[n][n];
double C[n][n];
int main() {
//populate the matrices with random values between 0.0 and 1.0
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
A[i][j] = (double) rand() / (double) RAND_MAX;
B[i][j] = (double) rand() / (double) RAND_MAX;
C[i][j] = 0;
}
}
struct timespec start, end;
double time_spent;
//matrix multiplication
clock_gettime(CLOCK_REALTIME, &start);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
for (int k = 0; k < n; k++) {
C[i][j] += A[i][k] * B[k][j];
}
}
}
clock_gettime(CLOCK_REALTIME, &end);
time_spent = (end.tv_sec - start.tv_sec) + (end.tv_nsec - start.tv_nsec) / 1000000000.0;
printf("Elapsed time in seconds: %f n", time_spent);
return 0;
}

但当我编译它时,gcc说:

main.c:27:19: error: 'CLOCK_REALTIME' undeclared (first use in this function)
clock_gettime(CLOCK_REALTIME, &start);
^~~~~~~~~~~~~~

我使用了MinGW的gcc-g++,如本教程中所述。

我刚刚从教程页面复制了C代码,并使用进行了编译

gcc -O3 main.c -o matrix

(我的源文件名为main.c(。

可能的重要信息:我在Windows 10上。

编辑:编译在Ubuntu 20.04上运行良好(如本文所述(。但是,你能帮我在Windows上编译它吗?

以下是我正在开发的基准程序的内容:

typedef long long ticks_t;
static ticks_t ticks_per_second;
#if OS_Windows
static ticks_t get_timer_resolution()
{
LARGE_INTEGER freq;
if (!QueryPerformanceFrequency(&freq)
|| !freq.QuadPart) {
printf("Error: cannot get Windows timer resolution.n");
exit(123);
}
return freq.QuadPart;
}
inline static ticks_t get_ticks()
{
LARGE_INTEGER ticks;
if (!QueryPerformanceCounter(&ticks)) {
printf("Error: cannot get Windows timer count.n");
exit(123);
}
return ticks.QuadPart;
}
#else       // NOT WINDOWS, should be Linux / Unix
static ticks_t get_timer_resolution()
{
return 10000000;
}
inline static ticks_t get_ticks()
{
struct timespec t;
clock_gettime(CLOCK_REALTIME, &t);
return (long long)t.tv_sec * 10000000 + (t.tv_nsec + 50) / 100;
}
#endif
[...]
int main() {
[...]
ticks_per_second = get_timer_resolution();

然后在我需要计时之前和之后使用get_ticks(),取差,并根据需要使用ticks_per_second进行缩放,例如

nticks = nticks * 1000000 / ticks_per_second;   // convert to microsecs

最新更新