Error trying getting clock resolution time - c

I'm using C and I'm trying to get Clock resolution but I get this value: 0.000000
Here is the code I'm using
#include <time.h>
#include<stdio.h>
double duration(struct timespec start, struct timespec end) {
return end.tv_sec - start.tv_sec
+ ((end.tv_nsec - start.tv_nsec ) / (double) 1000000000.0);
}
double getResolution(){
struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start);
do {
clock_gettime(CLOCK_MONOTONIC, &end);
} while (duration(start, end) == 0.0);
return duration(start, end);
}
int main(){
printf("%f",getResolution());
return 0;
}

You need to increase the precision in your printf("%f");. Using printf("%.12f"); would probably be enough to show some non-zero decimals.
Calculating the floating point duration in the while loop may cause the program to actually perform that calculation if the compiler isn't clever enough to figure out that you only need to see if the clock has changed at all. You could just do a memcmp to compare start and end instead.
Don't take the struct timespecs by value in your duration function. Supply pointers to the function instead. It should be cheaper.
Use the clock_getres function to get the resolution. The runtime value you get with your homebrewed solution depends on what speed the CPU is currently running at etc.
Example:
#include <stdio.h>
#include <string.h>
#include <time.h>
// taking the arguments via pointers:
double duration(const struct timespec* start, const struct timespec* end) {
return end->tv_sec - start->tv_sec +
((end->tv_nsec - start->tv_nsec) / 1000000000.0);
}
double getResolution() {
struct timespec start = {0}, end = {0};
clock_gettime(CLOCK_MONOTONIC, &start);
do {
clock_gettime(CLOCK_MONOTONIC, &end);
// using memcmp below:
} while (memcmp(&start, &end, sizeof start) == 0);
return duration(&start, &end);
}
int main() {
struct timespec base = {0}, res;
// using the proper function to get the resolution:
clock_getres(CLOCK_MONOTONIC, &res);
// comparing the results:
printf("clock_getres = %.12f\n", duration(&base, &res));
printf("getResolution = %.12f\n", getResolution());
}
Demo

Related

How to define C API to get current time count in nanosecond?

I need to define C API ex. GetTimerCountInNS(void) to get current TimerCount in Nanosecond, so using this API call I can calculate total execution time of some work done in nanosecond. Can someone suggest me what is wrong with my GetTimerCountInNS function as when I am calculating total execution time it shows incorrect execution time however for MilliSecond it shows correct one.
I already checked other query related to same one but I could not found exact answer.As I dont want to write all equation into main code when calculating time in nanosecond.
I need to use custom API to get count in Nanosecond and by getting different of start and stop time count I need to get total execution time.
How to get current timestamp in nanoseconds in linux using c
Calculating Function time in nanoseconds in C code
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdint.h>
#include <time.h>
#define BILLION 1000000000L;
// This API provides incorrect time in NS duration
uint64_t GetTimerCountInNS(void)
{
struct timespec currenttime;
clock_gettime( CLOCK_REALTIME, &currenttime);
//I am not sure here how to calculate count in NS
return currenttime.tv_nsec;
}
// This API provides correct time in MS duration
uint64_t GetTimerCountInMS(void)
{
struct timespec currenttime;
clock_gettime( CLOCK_REALTIME, &currenttime);
return (1000 * currenttime.tv_sec) + ((double)currenttime.tv_nsec / 1e6);
}
int main( int argc, char** argv )
{
struct timespec start, stop;
uint64_t start_ns,end_ns;
uint64_t start_ms,end_ms;
clock_gettime( CLOCK_REALTIME, &start);
start_ms = GetTimerCountInMS();
start_ns = GetTimerCountInNS();
int f = 0;
sleep(3);
clock_gettime( CLOCK_REALTIME, &stop);
end_ms = GetTimerCountInMS();
end_ns = GetTimerCountInNS();
double total_time_sec = ( stop.tv_sec - start.tv_sec ) + (double)( stop.tv_nsec - start.tv_nsec ) / (double)BILLION;
printf( "time in sec \t: %lf\n", total_time_sec );
printf( "time in ms \t: %ld\n", (end_ms - start_ms) );
printf( "time in ns \t: %ld\n", (end_ns - start_ns) );
return EXIT_SUCCESS;
}
Output:
time in sec : 3.000078
time in ms : 3000
time in ns : 76463 // This shows wrong time
A fix:
uint64_t GetTimerCountInNS(void) {
struct timespec currenttime;
clock_gettime(CLOCK_REALTIME, &currenttime);
return UINT64_C(1000000000) * currenttime.tv_sec + currenttime.tv_nsec;
}
In the return, a uint64_t constant is used to promote all other operands of the binary arithmetic operators to uint64_t, in addition to converting seconds to nanoseconds.

using gettimeofday() equivalents on windows

I'm trying to use 2 different equivalents for UNIX's gettimeofday() function on Windows, using Visual Studio 2013.
I took the first one from here. As the second one, I'm using the _ftime64_s function, as explained here.
They work, but not as I expected. I want to get different values when printing the seconds, or at least the milliseconds, but I get the same value for the printings with gettimeofday() (mytime1 & mytime2) and with _ftime64_s (mytime3 & mytime4).
However, it worth mentioning that the value of the milliseconds is indeed different between these two functions (that is, the milliseconds value of mytime1/mytime2 is different from mytime3/mytime4).
Here's my code:
#include <stdio.h>
#include <Windows.h>
#include <stdint.h>
#include <sys/timeb.h>
#include <time.h>
#define WIN32_LEAN_AND_MEAN
int gettimeofday(struct timeval * tp, struct timezone * tzp)
{
// Note: some broken versions only have 8 trailing zero's, the correct epoch has 9 trailing zero's
static const uint64_t EPOCH = ((uint64_t)116444736000000000ULL);
SYSTEMTIME system_time;
FILETIME file_time;
uint64_t time;
GetSystemTime(&system_time);
SystemTimeToFileTime(&system_time, &file_time);
time = ((uint64_t)file_time.dwLowDateTime);
time += ((uint64_t)file_time.dwHighDateTime) << 32;
tp->tv_sec = (long)((time - EPOCH) / 10000000L);
tp->tv_usec = (long)(system_time.wMilliseconds * 1000);
return 0;
}
int main()
{
/* working with struct timeval and gettimeofday equivalent */
struct timeval mytime1;
struct timeval mytime2;
gettimeofday(&(mytime1), NULL);
gettimeofday(&(mytime2), NULL);
printf("Seconds: %d\n", (int)(mytime1.tv_sec));
printf("Milliseconds: %d\n", (int)(mytime1.tv_usec));
printf("Seconds: %d\n", (int)(mytime2.tv_sec));
printf("Milliseconds: %d\n", (int)(mytime2.tv_usec));
/* working with _ftime64_s */
struct _timeb mytime3;
struct _timeb mytime4;
_ftime64_s(&mytime3);
_ftime64_s(&mytime4);
printf("Seconds: %d\n", mytime3.time);
printf("Milliseconds: %d\n", mytime3.millitm);
printf("Seconds: %d\n", mytime4.time);
printf("Milliseconds: %d\n", mytime4.millitm);
return (0);
}
I tried other format specifiers (%f, %lu) and castings ((float), (double), (long), (size_t)), but it didn't matter. Suggestions will be welcomed.
QueryPerformanceCounter is used for accurate timing on windows. Usage can be as follows:
uint64_t microseconds()
{
LARGE_INTEGER fq, t;
QueryPerformanceFrequency(&fq);
QueryPerformanceCounter(&t);
return (1000000 * t.QuadPart) / fq.QuadPart;
}
This does not work with any EPOCH as far as I know. For that you need GetSystemTimePreciseAsFileTime which is only available on Windows 8 and higher.
uint64_t MyGetSystemTimePreciseAsFileTime()
{
HMODULE lib = LoadLibraryW(L"kernel32.dll");
if (!lib) return 0;
FARPROC fp = GetProcAddress(lib, "GetSystemTimePreciseAsFileTime");
ULARGE_INTEGER largeInt;
largeInt.QuadPart = 0;
if (fp)
{
T_GetSystemTimePreciseAsFileTime* pfn = (T_GetSystemTimePreciseAsFileTime*)fp;
FILETIME fileTime = { 0 };
pfn(&fileTime);
largeInt.HighPart = fileTime.dwHighDateTime;
largeInt.LowPart = fileTime.dwLowDateTime;
}
FreeLibrary(lib);
return largeInt.QuadPart;
}
int main()
{
uint64_t t1 = microseconds();
uint64_t t2 = microseconds();
printf("t1: %llu\n", t1);
printf("t2: %llu\n", t2);
return (0);
}

clock_gettime API is giving negative values

I want current system time in micro seconds, so i have written a program using clock_gettime But it is returning negative values some times. Can someone help me on this.
int main(void) {
struct timespec tms;
/* The C11 way */
/* if (! timespec_get(&tms, TIME_UTC)) { */
/* POSIX.1-2008 way */
if (clock_gettime(CLOCK_REALTIME,&tms)) {
return -1;
}
/* seconds, multiplied with 1 million */
long long micros = tms.tv_sec * 1000000;
/* Add full microseconds */
micros += tms.tv_nsec/1000;
printf("Microseconds: %lld\n",micros);
return 0;
}
Hope the below code helps you:
#include<stdio.h>
#include<math.h>
#include<time.h>
void get_time_in_ms()
{
long ms;
time_t time;
struct timespec spec;
char tm[14];
clock_gettime(CLOCK_REALTIME, &spec);
time = spec.tv_sec;
ms = round(spec.tv_nsec / 1000000 ); // Convert nanoseconds to milliseconds
printf("Current time: %lu.%03ld seconds since the Epoch\n", time, ms);
sprintf(tm,"%lu%03ld",time, ms);
printf("Time : %s\n", tm);
}
void main() {
get_time_in_ms();
}

Getting Negative Values Using clock_gettime

In the following program, I have tried to measure the execution time of a job(for loop). Most of the time it works fine, however, sometimes, it returns negative values!! My first guess is that the variable may get overflowed. Can anyone please let me whether I am right or not? How can I solve the problem?
Thanks
int main(int argc, char **argv)
{
long int ST;
long int ET;
struct timespec gettime_now;
clock_gettime(CLOCK_REALTIME, &gettime_now);
ST= gettime_now.tv_nsec;
for (i=0; i < 1000; i++)
a[i]=b[i];
clock_gettime(CLOCK_REALTIME, &gettime_now);
ET= gettime_now.tv_nsec;
printf("Time diff: %ld\n", ET-ST);
}
You are neglecting tv_sec of struct timespec in both the cases and just using nano-second which is not correct as ST and EV's tv_nsec may be of different second's.
From man,
tv_sec - represents seconds since epoch
tv_nsec - current second in nano-second precision (1/1000000000 sec)
It is better to write own function to find the difference. Sample code (not tested),
timespec diff(timespec start, timespec end)
{
timespec temp;
if ((end.tv_nsec-start.tv_nsec)<0
{
temp.tv_sec = end.tv_sec-start.tv_sec-1;
temp.tv_nsec = 1000000000+end.tv_nsec-start.tv_nsec;
}
else
{
temp.tv_sec = end.tv_sec-start.tv_sec;
temp.tv_nsec = end.tv_nsec-start.tv_nsec;
}
return temp;
}
Refer this for actual diff function and example.

millisecond precision timing of functions in C - crossplatform

Is there a way to get milliseconds precision, accurate (at least within a few ms) times in C using a cross-platform approach?
on a POSIX system I can use sys/time.h, but that is not cross-platform.
the stdlib time() function only gives second level precision
I haven't found a cross-platform solution to measuring time in C, per se. However, what I do is use almost identical functions for Unix and Windows. I created this gist because I always have to re-look this up every time. In short:
Unix
#include <time.h>
long diff_micro(struct timespec *start, struct timespec *end)
{
/* us */
return ((end->tv_sec * (1000000)) + (end->tv_nsec / 1000)) -
((start->tv_sec * 1000000) + (start->tv_nsec / 1000));
}
long diff_milli(struct timespec *start, struct timespec *end)
{
/* ms */
return ((end->tv_sec * 1000) + (end->tv_nsec / 1000000)) -
((start->tv_sec * 1000) + (start->tv_nsec / 1000000));
}
int main(int argc, char **argv)
{
struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start);
// Activity to be timed
sleep(1000);
clock_gettime(CLOCK_MONOTONIC, &end);
printf("%ld us\n", diff_micro(&start, &end));
printf("%ld ms\n", diff_milli(&start, &end));
return 0;
}
source for Unix solution
Win32
#include <Windows.h>
long diff_micro(LARGE_INTEGER *start, LARGE_INTEGER *end)
{
LARGE_INTEGER Frequency, elapsed;
QueryPerformanceFrequency(&Frequency);
elapsed.QuadPart = end->QuadPart - start->QuadPart;
elapsed.QuadPart *= 1000000;
elapsed.QuadPart /= Frequency.QuadPart;
return elapsed.QuadPart;
}
long diff_milli(LARGE_INTEGER *start, LARGE_INTEGER *end)
{
LARGE_INTEGER Frequency, elapsed;
QueryPerformanceFrequency(&Frequency);
elapsed.QuadPart = end->QuadPart - start->QuadPart;
elapsed.QuadPart *= 1000;
elapsed.QuadPart /= Frequency.QuadPart;
return elapsed.QuadPart;
}
int main(int argc, char **argv)
{
LARGE_INTEGER StartingTime, EndingTime;
QueryPerformanceCounter(&StartingTime);
// Activity to be timed
Sleep(1000);
QueryPerformanceCounter(&EndingTime);
printf("%ld us\n", diff_micro(&StartingTime, &EndingTime));
printf("%ld ms\n", diff_milli(&StartingTime, &EndingTime));
return 0;
}
source used for Win32 solution
You can try something like this:-
#include <time.h>
clock_t uptime = clock() / (CLOCKS_PER_SEC / 1000);
See this Link
The best way is using std::chrono
#include <chrono>
...
auto begin = std::chrono::high_resolution_clock::now();
...
auto end = std::chrono::high_resolution_clock::now();
elapsedTime = std::chrono::duration_cast<std::chrono::milliseconds>(end - begin).count();

Resources