2

I know there is <chrono> in c++ and std::chrono::high_resolution_clock::now() can get the exact time of type std::chrono::high_resolution_clock::time_point. However, I am using raw C language so it is impossible to call this function. The time() function can only get second level time.

My final target is to measure the running time of a multi-thread program. The clock() function will sum the clocks of all threads up so it can not be used to measure the running time.

Steven Yang
  • 153
  • 5
  • 1
    Clock as in accurate benchmarking clock, or clock as in accurate time of the day? In either case, it is system-specific. – Lundin Mar 02 '20 at 09:05
  • 1
    POSIX documents [`clock_*()` functions](https://pubs.opengroup.org/onlinepubs/9699919799/functions/clock_getres.html) which may do what you want. – pmg Mar 02 '20 at 09:08
  • @pmg Thanks! It seem that I can use `timespec_get()` to get the accurate time. – Steven Yang Mar 02 '20 at 09:19
  • *I know there is `` in c++ and `std::chrono::high_resolution_clock::now()` can get the exact time of type `std::chrono::high_resolution_clock::time_point`.* On any specific platform, there's nothing in C++ that has access to any clock more accurate than C can access. C++ isn't going to be more accurate than C. They both have access to the **same** underlying clock implementations. C++ just hides the exact implementation(s) under portable abstractions. – Andrew Henle Mar 02 '20 at 11:07

2 Answers2

1

Unfortunately, the higher-resolution clocks tend to differ a bit from platform to platform. It also depends what type of clock you're interested in (such as real time, CPU time, or monotonic time).

Based on your use case, you probably want monotonic time…

If you're on a POSIX operating system, clock_gettime is usually the way to go, but even then which clocks are available can vary a lot. For example, macOS doesn't support CLOCK_MONOTONIC, but it does have other APIs you can use to get the monotonic time.

If you're on Windows you'll probably want to use QueryPerformanceCounters.

If you want something to abstract away the differences, I put something together a while back.

nemequ
  • 16,623
  • 1
  • 43
  • 62
0

The following snippet will give the exact system time :

time_t now;
time(&now);
struct tm* now_tm;
now_tm = localtime(&now);
char dte[80];
strftime (dte, 80, "%Y-%m-%d %I:%M:%S", now_tm);
  • 1
    Not enough resolution for OP's intents, I believe. OP wants more than second resolution, something like "6 hundredths of a second" or "2718 microseconds" – pmg Mar 02 '20 at 10:19