Skip to content

Instantly share code, notes, and snippets.

@zhu-yifang
Created September 23, 2022 03:45
Show Gist options
  • Save zhu-yifang/38e90f4a15e1c524ab4a2747ecf8f5f1 to your computer and use it in GitHub Desktop.
Save zhu-yifang/38e90f4a15e1c524ab4a2747ecf8f5f1 to your computer and use it in GitHub Desktop.
#include <iostream> // for cin, cout
#include <time.h> // for clock_gettime
#include <cstdlib> // for rand, srand
using namespace std;
// Function to generate a number from [-bound, bound]
template <typename T>
T GenerateRandomNumber(double bound)
{
return (rand() / (double)RAND_MAX) * 2 * bound - bound;
}
// Create a array of 'size' floats in the range [-bound, bound]
template <typename T>
T *GenerateRandomArray(int size, double bound)
{
T *array = new T[size];
for (int i = 0; i < size; i++)
{
array[i] = GenerateRandomNumber<T>(bound);
}
return array;
}
template <typename T>
void UpdateCoords(T *xs, T *ys, T *zs, T *vx, T *vy, T *vz, int size)
{
for (int i = 0; i < size; i++)
{
xs[i] += vx[i];
ys[i] += vy[i];
zs[i] += vz[i];
}
}
template <typename T>
void test(int size, int iters)
{
cout << "Testing with size = " << size << " and iters = " << iters << endl;
T *xs = GenerateRandomArray<T>(size, 1000);
T *ys = GenerateRandomArray<T>(size, 1000);
T *zs = GenerateRandomArray<T>(size, 1000);
T *vx = GenerateRandomArray<T>(size, 1);
T *vy = GenerateRandomArray<T>(size, 1);
T *vz = GenerateRandomArray<T>(size, 1);
timespec start, end;
if (clock_gettime(CLOCK_MONOTONIC, &start) != 0)
{
cout << "Error getting start time" << endl;
}
for (int i = 0; i < iters; i++)
{
UpdateCoords<T>(xs, ys, zs, vx, vy, vz, size);
}
if (clock_gettime(CLOCK_MONOTONIC, &end) != 0)
{
cout << "Error getting end time" << endl;
}
double start_us = start.tv_sec * 1e6 + start.tv_nsec / 1e3;
double end_us = end.tv_sec * 1e6 + end.tv_nsec / 1e3;
double total_time_us = end_us - start_us;
double chksum = 0;
for (int i = 0; i < size; i++)
{
chksum += xs[i] + ys[i] + zs[i];
}
cout << "Mean time per coordinate: " << total_time_us / (size * iters) << " us" << endl;
cout << "Checksum: " << chksum << endl;
}
int main()
{
srand(20220921);
cout << "Testing float" << endl;
test<float>(224, 1000000);
cout << "Testing double" << endl;
test<double>(224, 1000000);
cout << "Testing int8_t" << endl;
test<int8_t>(224, 1000000);
cout << "Testing int16_t" << endl;
test<int16_t>(224, 1000000);
cout << "Testing int32_t" << endl;
test<int32_t>(224, 1000000);
cout << "Testing int64_t" << endl;
test<int64_t>(224, 1000000);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment