Page 1 of 1

What's the preferred way to get a system time (like millis() on Arduino)

Posted: 20 Mar 2017, 09:28
by KarlZeilhofer
Hi,

since I've never wrote programms for realtime systems on linux, I wonder, how I get a precise time?

On Arduino for example I use millis(), which returns the milli seconds since start of the programm.

Is <time.h> with clock() and CLOCKS_PER_SECOND the correct way?

Code: Select all

#include <time.h>
...
int millis(){
	static clock_t start;

	static bool firstRun=true;
	if(firstRun){
		firstRun = false;
		start = clock();
	}

	clock_t now = clock();
	clock_t diff = now-start;

	double t = (double)diff/CLOCKS_PER_SEC;

	return t*1000;
}
Kind Regards, Karl

Re: What's the preferred way to get a system time (like millis() on Arduino)

Posted: 21 Mar 2017, 04:59
by KarlZeilhofer
I just tested a minimal example on the RevPi, but clocks() from <time.h> seems to return a wrong number, see screenshot.
The execution, according to date needed about 45s, but the example code just counted 30s.
Has this to do with the real time kernel? What else can be used?

You can try this code also on tutorialspoint.com: https://goo.gl/YszZBX
There the timing seems to be okay.

What else can be used to get a proper time?