C/timer

From Attie's Wiki
Revision as of 12:37, 1 November 2012 by Attie (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

These macros can be used to perform basic timing on a part of code.

They use braced ({}) contexts.

  • TIMER_START_HERE opens the context and grabs the 'start time'
  • TIMER_GET_HERE allows the user to grab the time since TIMER_START_HERE in either a long long int (as nanoseconds), or in a struct timespec.
  • TIMER_PRINT_HERE will printf the given message and parameters, along with file, line number and time taken - two parameters are required (sorry)
  • TIMER_SPEED_HERE will print the rate in MB/s with a given label
  • TIMER_END_HERE closes the context, and prints a message (same arguments as TIMER_PRINT_HERE

It is worth noting that due to the use of contexts, any TIMER_START_HERE that is 'inside' a TIMER_START_HERE, will have the effect of moving the start time. Once a TIMER_END_HERE is used, this start time will revert to that of the 'outer' TIMER_START_HERE.

#ifndef TIMER_H
#define TIMER_H
 
#include <time.h>
 
#define TIMER_START_HERE() \
	{	struct timespec timer_start; \
		const int timer_start_line = __LINE__; \
		clock_gettime(CLOCK_REALTIME, &timer_start);
 
#define TIMER_GET_HERE(v, p) \
		{	struct timespec __timer; \
			clock_gettime(CLOCK_REALTIME, &__timer); \
			__timer.tv_sec -= timer_start.tv_sec; \
			__timer.tv_nsec -= timer_start.tv_nsec; \
			if (__timer.tv_nsec < 0) { \
				__timer.tv_sec--; \
				__timer.tv_nsec += 1000000000; \
			} \
			if ((v)) *((unsigned long*)(v)) = (__timer.tv_sec * 1000000000) + __timer.tv_nsec; \
			if ((p)) memcpy(((struct timespec*)(p)), &__timer, sizeof(__timer)); \
		}
 
#define TIMER_PRINT_HERE(fmt, ...) \
		{	struct timespec timer_diff; \
			TIMER_GET_HERE(NULL, &timer_diff); \
			fprintf(stderr, "###### TIMER ###### -> file:%s lines:%d-%d took:%ld.%09ld seconds  " fmt "\n", __FILE__, timer_start_line, __LINE__, timer_diff.tv_sec, timer_diff.tv_nsec, __VA_ARGS__); \
		}
 
#define TIMER_SPEED_HERE(label, size) \
		{	unsigned long diff; \
			float speed; \
			TIMER_GET_HERE(&diff, NULL); \
			speed = diff; \
			speed /= 1000; \
			speed = size / speed; \
			fprintf(stderr, "===== SPEED (%s): %d byes in %dns -> %.2f MB/s\n", label, size, diff, speed); \
		}
 
#define TIMER_END_HERE(fmt, ...) \
		TIMER_PRINT_HERE(fmt, __VA_ARGS__); \
	}
 
 
#endif /* TIMER_H */
Personal tools
Namespaces

Variants
Actions
Navigation
Toolbox