【问题标题】:clock_gettime: identifier not found in Visual Studio in Windows 10clock_gettime:在 Windows 10 的 Visual Studio 中找不到标识符
【发布时间】:2019-12-31 06:34:39
【问题描述】:

我尝试在 Visual Studio 2015 的 clock_gettime 的帮助下运行这个程序来执行函数所花费的时间。 我已经按照这里的参考:https://www.cs.rutgers.edu/~pxk/416/notes/c-tutorials/gettime.html

#include <iostream>
#include <stdio.h>  /* for printf */
#include <stdint.h> /* for uint64 definition */
#include <stdlib.h> /* for exit() definition */
#include <ctime>
#include<windows.h>
#define _POSIX_C_SOURCE 200809L
#define BILLION 1000000000L

void fun() {

    Sleep(3);
}
int main()
{
    struct timespec start, end;
    int i;
    uint64_t diff;

    /* measure monotonic time */
    clock_gettime(CLOCK_MONOTONIC, &start); /* mark start time */
    fun();
    clock_gettime(CLOCK_MONOTONIC, &end);   /* mark the end time */
    diff = BILLION * (end.tv_sec - start.tv_sec) + end.tv_nsec - start.tv_nsec;
    printf("elapsed time = %llu nanoseconds\n", (long long unsigned int) diff);

    system("pause");
    return 0;
}

我尝试在 Linux 中运行,它运行良好。但在 Windows 中,VS 2015 显示错误。

'CLOCK_MONOTONIC' : undeclared identifier 
'clock_gettime': identifier not found

请建议我如何修复此错误或如何在 Visual Studio 2015 中查找经过的时间。谢谢。

【问题讨论】:

  • 如果您想使用 POSIX C 函数 clock_gettime(),那么 (a) 实现必须提供它,并且 (b) 您必须在包含第一个标头之前指定 _POSIX_C_SOURCE。如果您使用的是 C++,那么您有标准的 C++ 选项——它们更有可能跨平台可靠地工作。 (不知道是 Windows 10 还是 MSVS 2015 提供的,2015 年的时候 macOS 没有提供,现在提供了。)

标签: c++ c visual-studio time clock


【解决方案1】:

函数clock_gettime() 由POSIX 定义。 Windows 不符合 POSIX。

这是 a link 将 clock_gettime() 移植到 Windows 的旧帖子。

对于 Windows,我会使用 std::chrono 库。

简单的例子是:

 #include <chrono>
    auto start = std::chrono::high_resolution_clock::now();
    func();
    auto end = std::chrono::high_resolution_clock::now();

    std::chrono::duration<float> duration = end - start;
    printf("Duration : %f", duration.count());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-25
    • 1970-01-01
    • 2011-04-11
    • 1970-01-01
    • 2016-04-03
    • 1970-01-01
    • 1970-01-01
    • 2017-01-03
    相关资源
    最近更新 更多