Welcome!

Welcome to the official BlackBerry Support Community Forums.

This is your resource to discuss support topics with your peers, and learn from each other.

inside custom component

Native Development

Reply
Highlighted
Contributor
Posts: 23
Registered: ‎06-06-2012
My Device: Simulator
My Carrier: n/a
Accepted Solution

Invalid values for clock() when in main application loop

I've written the following test code that determines elapsed values for clock() for every second change reported by time(NULL):

 

static time_t	thisTime = 0;
static clock_t	clocks = 0;
time_t nextTime = time(NULL);

if (nextTime != thisTime)
{
	clock_t	nextClocks = clock();
	printf("%d\n", nextClocks - clocks);
	fflush(stdout);

	thisTime = nextTime;
	clocks = nextClocks;
}

 Normally, I would expect this to print values close to CLOCKS_PER_SEC, ie. 1,000,000.

 

However, if I add this to the render loop of any of the sample apps, I get extremely wonky values that are both inconsistent and much too small.

 

For instance, I added it right after the call to render() in GoodCitizen (as well as adding #include <time.h> to the top of the file), and got these values:

 

10998
4000
4999
2000
2000
1000
1001
8998
8000
5999
7999
5999
12999
13998

 I get the same thing with HelloWorldDisplay, and basically anything that uses a Blackberry event/render loop. The apps themselves appear to be running at full framerate (although if performance were an issue I'd expect numbers that were too large, not too small).

 

On the other hand, if I encase the test code in while (true) { ... }, essentially causing the app to hang in a tight loop, I get numbers much nearer my expected values:

 

988850
997848
993849
995849
992849
990849
996849
991849
987850
987850
940857
975852
988850
993849

 So something about the Blackberry event/render loop is causing clock() to report incorrect values.

 

Can anyone explain this? What is the correct procedure for determining sub-second intervals?

 

Thanks,


Dan.

BlackBerry Development Advisor
Posts: 683
Registered: ‎11-29-2011
My Device: PRIV
My Carrier: Rogers

Re: Invalid values for clock() when in main application loop

If you read the clock() documentation:

https://developer.blackberry.com/native/reference/com.qnx.doc.neutrino.lib_ref/topic/c/clock.html

You will note that clock() measures CPU time, not wall-clock-time for your process.  This explains why your while(1) {} loop would measure something close to 1000000 microseconds over a 1-second interval, because it's running-ready.

Your other tests must be spending a bunch of time in blocking system calls, which don't count towards clock() time as your process is not actually running.

 

If you want to measure wall-clock-time, use ClockTime() to query the CLOCK_MONOTONIC clock, or something equivalent.  clock_gettime() may be more portable than ClockTime().

 

Cheers,

Sean