【发布时间】: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 中查找经过的时间。谢谢。
【问题讨论】:
-
使用 std::chrono。 docs.microsoft.com/en-us/cpp/standard-library/…
-
如果您想使用 POSIX C 函数
clock_gettime(),那么 (a) 实现必须提供它,并且 (b) 您必须在包含第一个标头之前指定_POSIX_C_SOURCE。如果您使用的是 C++,那么您有标准的 C++ 选项——它们更有可能跨平台可靠地工作。 (不知道是 Windows 10 还是 MSVS 2015 提供的,2015 年的时候 macOS 没有提供,现在提供了。)
标签: c++ c visual-studio time clock