1

I try running this program to execute the time taken for function by the help of clock_gettime in Visual Studio 2015. I have followed the reference from here: 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;
}

I tried running in Linux, it works fine. But in Windows, VS 2015 shows error.

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

Please suggest me how to fix this error or how to find the elapsed time in Visual studio 2015. Thanks.

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
Ratnesh
  • 1,554
  • 3
  • 12
  • 28
  • 1
    Use std::chrono. https://learn.microsoft.com/en-us/cpp/standard-library/chrono?view=vs-2019 – Igor R. Aug 27 '19 at 06:14
  • 1
    If you want to use the POSIX C function [`clock_gettime()`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/clock_gettime.html), then (a) the implementation must provide it, and (b) you must specify `_POSIX_C_SOURCE` before you include the first header. If you're using C++, you have standard C++ options — that are more likely to work reliably across platforms. (I don't know whether Windows 10 or MSVS 2015 provides it; in 2015, macOS didn't provide the function, though it does now.) – Jonathan Leffler Aug 27 '19 at 06:45

1 Answers1

3

Function clock_gettime() is defined by POSIX. Windows is not POSIX compliant.

Here's a link to old post of porting clock_gettime() to Windows.

For Windows I would use std::chrono library.

Simple example is :

 #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());
Samuel B.
  • 156
  • 5