I wanted to see which would access faster, a struct or a tuple, so I wrote a small program. However, when it finishes running the time recorded is 0.000000 for both. I'm pretty sure the program isn't finishing that fast(running on an online compiler since I am away from home)
#include <iostream>
#include <time.h>
#include <tuple>
#include <cstdlib>
using namespace std;
struct Item
{
int x;
int y;
};
typedef tuple<int, int> dTuple;
int main() {
printf("Let's see which is faster...\n");
//Timers
time_t startTime;
time_t currentTimeTuple;
time_t currentTimeItem;
//Delta times
double deltaTimeTuple;
double deltaTimeItem;
//Collections
dTuple tupleArray[100000];
struct Item itemArray[100000];
//Seed random number
srand(time(NULL));
printf("Generating tuple array...\n");
//Initialize an array of tuples with random ints
for(int i = 0; i < 100000; ++i)
{
tupleArray[i] = dTuple(rand() % 1000,rand() % 1000);
}
printf("Generating Item array...\n");
//Initialize an array of Items
for(int i = 0; i < 100000; ++i)
{
itemArray[i].x = rand() % 1000;
itemArray[i].y = rand() % 1000;
}
//Begin timer for tuple array
time(&startTime);
//Iterate through the array of tuples and print out each value, timing how long it takes
for(int i = 0; i < 100000; ++i)
{
printf("%d: %d", get<0>(tupleArray[i]), get<1>(tupleArray[i]));
}
//Get the time it took to go through the tuple array
time(¤tTimeTuple);
deltaTimeTuple = difftime(startTime, currentTimeTuple);
//Start the timer for the array of Items
time(&startTime);
//Iterate through the array of Items and print out each value, timing how long it takes
for(int i = 0; i < 100000; ++i)
{
printf("%d: %d", itemArray[i].x, itemArray[i].y);
}
//Get the time it took to go through the item array
time(¤tTimeItem);
deltaTimeItem = difftime(startTime, currentTimeItem);
printf("\n\n");
printf("It took %f seconds to go through the tuple array\nIt took %f seconds to go through the struct Item array\n", deltaTimeTuple, deltaTimeItem);
return 0;
}
According to www.cplusplus.com/reference/ctime/time/, difftime should return the difference between two time_t.