commit 7c885bf8a80528f8a1e2401220f5bc4f58b7aa3e parent 8e63a85c27ce4688a3f063f74a3882db39d663a7 Author: Michael Savage <mikejsavage@gmail.com> Date: Fri Jan 8 21:05:06 +0000 Add Stats Diffstat:
stats.cc | | | 42 | ++++++++++++++++++++++++++++++++++++++++++ |
stats.h | | | 21 | +++++++++++++++++++++ |
diff --git a/stats.cc b/stats.cc @@ -0,0 +1,42 @@ +#include <stdio.h> +#include <math.h> + +#include "intrinsics.h" +#include "stats.h" + +void stats_init( Stats * stats ) { + *stats = { }; +} + +double stats_mean( const Stats * stats ) { + return stats->sum / stats->num_samples; +} + +double stats_stddev( const Stats * stats ) { + double variance = ( stats->sum_of_squares - ( stats->sum * stats->sum / stats->num_samples ) ); + return sqrt( variance ); +} + +void stats_record( Stats * stats, double x ) { + stats->sum += x; + stats->sum_of_squares += x * x; + + if( stats->num_samples == 0 ) { + stats->min = stats->max = x; + } + else { + if( x < stats->min ) stats->min = x; + if( x > stats->max ) stats->max = x; + } + + stats->num_samples++; +} + +void stats_print( const Stats * stats, const char * name ) { + printf( "[%s]\n\tn: %llu\n\tmean: %f\n\tstddev: %f\n\trange: %f to %f\n", + name, stats->num_samples, + stats_mean( stats ), stats_stddev( stats ), + stats->min, stats->max + ); +} + diff --git a/stats.h b/stats.h @@ -0,0 +1,21 @@ +#ifndef _STATS_H_ +#define _STATS_H_ + +#include "intrinsics.h" + +struct Stats { + double sum; + double sum_of_squares; + double min; + double max; + u64 num_samples; +}; + + +void stats_init( Stats * stats ); +double stats_mean( const Stats * stats ); +double stats_stddev( const Stats * stats ); +void stats_record( Stats * stats, double x ); +void stats_print( const Stats * stats, const char * name ); + +#endif // _STATS_H_