On Windows, how do you get time in nanoseconds in C?

4 min read
Visual C on Windows does not provide the POSIX clock_gettime or *nix gettimeofday functions. In these situations, hand rolled solutions proliferate. Since Visual Studio 2015 (cl version 19.00), the C11 function timespec_get has been available and is a better solution.
On Windows, how do you get time in nanoseconds in C? A. Sinan Unur July 18, 2021

I recently decided to go back to dabbling in OCaml. The easier path would have been to install it in a Linux VM and play with it there, but I decided to build it from source to use Microsoft's C compiler. The instructions are clear and easy to follow. The advantage of compiling with cl is that while the actual build does need the Cygwin tools, the resulting binaries have no restrictions on them as they are not linked with the Cygwin DLL.

After ocaml itself was built and installed, it was opam next. Similarly, build and install were uneventful, made easy by the availability of excellent instructions.

Once opam was installed and initialized, I tried opam install core to install JaneStreet's Core library. The installation failed because core_kernel depends on time_now and time_now does not compile with MS Visual C:

* install time_now v0.14.0 <><> Processing actions <><><><><><><><><><><><><><><><><><><><><><><><><><><><> ▼ retrieved time_now.v0.14.0 (cached) [ERROR] The compilation of time_now.v0.14.0 failed at "dune build -p time_now -j 1". #=== ERROR while compiling time_now.v0.14.0 ===================================# # context 2.1.0~rc2 | win32/x86_64 | ocaml.4.12.0 | https://opam.ocaml.org#6609b442 # path ~\.opam\default\.opam-switch\build\time_now.v0.14.0 # command ~\.opam\default\bin\dune.exe build -p time_now -j 1 # exit-code 1 # env-file ~\.opam\log\time_now-8632-6ce4ee.env # output-file ~\.opam\log\time_now-8632-6ce4ee.out ### output ### # cl src/time_now_stubs.obj (exit 2) # (cd _build/default/src && "C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\ VC\Tools\MSVC\14.29.30037\bin\HostX64\x64\cl.exe" -nologo -O2 -Gy- -MD…
A. Sinan Unur
Read full article