[ create a new paste ] login | about

Link: http://codepad.org/agPWItZS    [ raw code | fork ]

C++, pasted on Mar 27:
#include <stdlib.h> 
#include <stdio.h>

//OS X Specific hi res timer + headers
//Replace with your own high res timer if desired
#include <stdint.h>
#include <mach/mach_time.h>
double timer()
{
    static uint64_t start = -1;
    static double conversion = -1;
    if( start == -1 )
    {
		if(conversion == -1)
		{
			mach_timebase_info_data_t info;
			kern_return_t err = mach_timebase_info( &info );
			if( err == 0  )
			{
				conversion = 1e-9 * (double) info.numer / (double) info.denom;
			}
		}
	 	start = mach_absolute_time();
    }
	uint64_t elapsed = mach_absolute_time() - start;
	return conversion*(double)elapsed;
}

//We fill with roughly equal counts of positive and negative numbers to prevent
//overflow.
void fill( double *p, int n )
{
    for( int i = 0; i < n; i++ )
    {
        double val = (double)rand() / RAND_MAX;
        double sign_num = (double) rand()/RAND_MAX;
        int sign;
        if(sign_num > 0.5)
        {
            sign = +1;
        }
        else
        {
            sign = -1;
        }
        p[i] = sign*val;
    }
}

double sum(double a,double* X,int size)
{
	double total = 0.0;
	for(int i = 0;  i < size; ++i)
	{
		total += a*X[i];
	}
	return total;
}

#define KB 1024
int main()
{
    //Approximately half the L1 cache size of my machine
	int operand_size = (32*KB)/(sizeof(double)*2);
	printf("Operand size: %d\n", operand_size);
	double* X = new double[operand_size];
	fill(X,operand_size);

    double seconds = timer();
    double result;
    int n_iterations = 100000;
    for(int i = 0; i < n_iterations; ++i)
    {
        result = sum(3.5,X,operand_size);
        //result += rand();  
    }
    seconds = timer() - seconds; 

    double mflops = 2e-6*double(n_iterations*operand_size)/seconds;
    printf("Vector size %d: mflops=%.1f, result=%.1f\n",operand_size,mflops,result);
	return 0;
}


Create a new paste based on this one


Comments: