Lookup table for distances/ sqrt question

I made the code below to test which is faster, sqrt or using a lookup table with a ton of random floats and it turns out the first method, the function named method1 is faster. Is it because of caching or what.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <cmath>
#include <iostream>
#include <ctime>
#include <vector>

using namespace std;

double diffclock(clock_t clock1,clock_t clock2)
{
	double diffticks=clock1-clock2;
	double diffms=(diffticks*1000)/CLOCKS_PER_SEC;
	return diffms;
}
void method1(int limit)
{
	int max = 100;
	cout<<"method 1"<<endl;

	float distance;
	clock_t begin = clock();
	for(int count = 0; count < limit; count++)
	{
		float x1 = (float)rand()/(float)RAND_MAX + max;
		float x2 = (float)rand()/(float)RAND_MAX + max;
		float y1 = (float)rand()/(float)RAND_MAX + max;
		float y2 = (float)rand()/(float)RAND_MAX + max;
		float z1 = (float)rand()/(float)RAND_MAX + max;
		float z2 = (float)rand()/(float)RAND_MAX + max;
		distance = sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2)+(z1-z2)*(z1-z2));
	}
	clock_t end=clock();
	cout << "Time elapsed: " << double(diffclock(end,begin)) << " ms"<< endl;

}

int main()
{
	srand(time(NULL));

	method1(100000000);
	method1(100000000);
	method1(100000000);	

	return 0;
}
Last edited on
Hi lostwithcpp, i think it could be because you use vector < vector < vector <float > > > distance, which is a very expensive data structure.
Try converting this distance 3D vector into 1D array: float* distance.
Besides, since you are using different operations:

method1: conversion, /, +
method2: %

There could lead to some discrepancy, but not so much anyway.
I also forgot to put the sqrt in the second method but I guess the access time for vectors is slow.

I did what you told me and now method 2 is 2/3 the time of method 1 so it was the vector.
Last edited on
Topic archived. No new replies allowed.