simple StopWatch with roundtrip time source code

This snippet submitted by NickMa on 2013-07-05. It has been viewed 90500 times.
Rating of 7.4 with 495 votes

#define MAX_ROUNDTRIP_COUNT 32

typedef struct stopWatch_s {
	struct timeval eachTime[MAX_ROUNDTRIP_COUNT+1];
	uint16_t roundTripCount;
} stopWatch_t;

void stopWatch_start(stopWatch_t *stopWatch) {
	stopWatch->roundTripCount = 0;
	gettimeofday(stopWatch->eachTime, NULL);
}

int stopWatch_createRoundTrip(stopWatch_t *stopWatch) {
	if ( !timerisset(&stopWatch->eachTime[0]) ) return -1;

	if(stopWatch->roundTripCount >= MAX_ROUNDTRIP_COUNT) {
		fprintf(stderr, \\"RoundtripCount of %d reached\n\\", MAX_ROUNDTRIP_COUNT);
		return -1;
	}

	stopWatch->roundTripCount += 1;
	gettimeofday(&stopWatch->eachTime[stopWatch->roundTripCount], NULL);
	return 0;
}

int stopWatch_printLatestTime(stopWatch_t *stopWatch) {
	if ( !timerisset(&stopWatch->eachTime[0]) ) return -1;

	struct timeval timeFromStart, timeFromLastRoundtrip;
	gettimeofday(&timeFromStart, NULL);
	gettimeofday(&timeFromLastRoundtrip, NULL);

	/* calculate time deltas */
	timersub(&timeFromStart, &stopWatch->eachTime[0], &timeFromStart);
	if( stopWatch->roundTripCount == 0 ) {
		timerclear(&timeFromLastRoundtrip);
	} else {
		timersub(&stopWatch->eachTime[stopWatch->roundTripCount],
				 &stopWatch->eachTime[stopWatch->roundTripCount-1],
				&timeFromLastRoundtrip);
	}

	printf(\\"#%d delta:%ld.%06ld[s], sum:%ld.%06ld[s]\n\\",
    		stopWatch->roundTripCount,
    		timeFromLastRoundtrip.tv_sec, timeFromLastRoundtrip.tv_usec,
    		timeFromStart.tv_sec, timeFromStart.tv_usec);

    return 0;
}
 
 




More C and C++ source code snippets

Add a snippet!