OT: recommended way of timing two pieces of code in C

Ranjan Maitra maitra.mbox.ignored at inbox.com
Sat Feb 27 14:48:23 UTC 2016


On Sat, 27 Feb 2016 14:09:25 +0000 "Patrick O'Callaghan" <pocallaghan at gmail.com> wrote:

> On Sat, 2016-02-27 at 07:44 -0600, Ranjan Maitra wrote:
> > #define INTERVAL 1        /* number of milliseconds to go off */
> > 
> > int main() {
> >     double sum = 0;
> >     struct itimerval initial, updated;
> > 
> >     initial.it_value.tv_sec     = INTERVAL/1000000;
> >     initial.it_value.tv_usec    = (INTERVAL/1000000) * 1000000;
> 
> To start with, these are both integer values, so you're initializing
> them to 0. There may be other bugs but I stopped looking when I saw
> this.
> 
> poc
> -- 

OK, thanks! So, I tried this:

#include <sys/time.h>
#include <stdlib.h>
#include <stdio.h>
#include <limits.h>

#define INTERVAL 1        /* number of milliseconds to go off */

int main() {
	double sum = 0;
	struct itimerval initial, updated;
	
	initial.it_value.tv_sec     = INTERVAL;
	initial.it_value.tv_usec    = INT_MAX;
	initial.it_interval = initial.it_value;

	printf("%ld\n", initial.it_value.tv_usec);
	
	if (setitimer(ITIMER_VIRTUAL, &initial, NULL) == -1) {
		perror("error calling setitimer()");
		exit(1);
	}

	for (unsigned int i; i < 100000; i++) 
		sum += 1./i;
	
	if (getitimer(ITIMER_REAL, &updated) == -1) {
		perror("error calling getitimer()");
		exit(1);
	}

	printf("Time started = %ld\n; Time taken = %ld\n: Time taken = %ld\n",
	       initial.it_value.tv_usec, updated.it_value.tv_usec,
	       initial.it_value.tv_usec - updated.it_value.tv_usec);
	return 0;
}


But now setitimer does not execute:-(

$gcc -o timer -std=c99 -Wall -pedantic getitimer.c -lrt -O3
$./timer
2147483647
error calling setitimer(): Invalid argument

Thanks!
Ranjan

____________________________________________________________
FREE 3D MARINE AQUARIUM SCREENSAVER - Watch dolphins, sharks & orcas on your desktop!
Check it out at http://www.inbox.com/marineaquarium




More information about the users mailing list