Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ---cycle_bench.h---
- #ifndef CYCLE_BENCH_H
- #define CYCLE_BENCH_H
- #include <asm/msr.h>
- #define BENCH_LOOP_NUM 1000
- typedef long long int int64;
- typedef struct _cycle_bench_context
- {
- // start is declared as volatile to prevent the compilator to optimize code.
- // The calculated overhead execution time is slightly more accurate.
- volatile int64 start;
- int64 cycles[ BENCH_LOOP_NUM ];
- int index;
- int64 total_cycles_mean;
- int64 total_cycles_std_dev;
- int64 overhead_cycles_mean;
- int64 overhead_cycles_std_dev;
- int64 section_cycles_mean;
- int64 section_cycles_std_dev;
- } cycle_bench_context;
- void init_cycle_bench( cycle_bench_context *ctx );
- void calc_cycle_bench( cycle_bench_context *ctx );
- static inline int64 getcpucycles()
- {
- unsigned long low;
- long high;
- rdtsc( low, high );
- return ( (int64)high << 32) | low;
- }
- #define BEGIN_BENCH_LOOP( ctx ) \
- for( (ctx)->index = 0; (ctx)->index < BENCH_LOOP_NUM; (ctx)->index++ ) \
- { \
- (ctx)->start = getcpucycles();
- #define END_BENCH_LOOP( ctx ) \
- (ctx)->cycles[ (ctx)->index ] = getcpucycles() - (ctx)->start; \
- }
- #endif
- --- cycle_bench.c ---
- #include "cycle_bench.h"
- #include <string.h>
- #include <math.h>
- void init_cycle_bench( cycle_bench_context *ctx )
- {
- memset( ctx, 0, sizeof( cycle_bench_context ));
- BEGIN_BENCH_LOOP( ctx );
- END_BENCH_LOOP( ctx );
- calc_cycle_bench( ctx );
- ctx->overhead_cycles_mean = ctx->total_cycles_mean;
- ctx->overhead_cycles_std_dev = ctx->total_cycles_std_dev;
- }
- void calc_cycle_bench( cycle_bench_context *ctx )
- {
- int i;
- int64 tmp=0;
- for( i = 0; i < BENCH_LOOP_NUM; i++ )
- tmp += ctx->cycles[i];
- ctx->total_cycles_mean = tmp / BENCH_LOOP_NUM;
- tmp = 0;
- for( i = 0; i < BENCH_LOOP_NUM; i++ )
- tmp += pow( ctx->total_cycles_mean - ctx->cycles[i], 2 );
- ctx->total_cycles_std_dev = sqrt( tmp / BENCH_LOOP_NUM );
- ctx->section_cycles_mean = ctx->total_cycles_mean - \
- ctx->overhead_cycles_mean;
- ctx->section_cycles_std_dev = ctx->total_cycles_std_dev + \
- ctx->overhead_cycles_std_dev;
- }
- --- how to use it ---
- cycle_bench_context ctx;
- init_cycle_bench( &ctx );
- BEGIN_BENCH_LOOP( &ctx );
- struct timeval tv;
- gettimeofday( &tv, NULL );
- END_BENCH_LOOP( &ctx );
- calc_cycle_bench( &ctx );
- // ctx.section_cycles_mean and ctx.section_cycles_std_dev contains the data
Advertisement
Add Comment
Please, Sign In to add comment