【发布时间】:2015-01-18 19:17:12
【问题描述】:
我想看看哪个访问更快,一个结构体还是一个元组,所以我写了一个小程序。但是,当它完成运行时,两者的记录时间都是 0.000000。我很确定程序没有那么快完成(因为我不在家,所以在在线编译器上运行)
#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;
}
根据 www.cplusplus.com/reference/ctime/time/,difftime 应该返回两个 time_t 之间的差。
【问题讨论】:
-
永远不要在基准循环中包含
printf语句。他们只会破坏任何时间。 -
我认为没有理由怀疑您的程序可以在不到一秒的时间内完成。
-
我不明白,
tuple是一个结构。如果时机很重要,我会很感兴趣。检查汇编语言列表以验证访问tuple与访问您的结构的汇编语言是否不同。 -
您的程序可以运行,但时钟的分辨率可能太低。如果我添加一个睡眠,时间是准确的。但是请注意,您应该交换
difftime的参数,除非您希望报告负间隔。由于您似乎无论如何都在使用 C++11,请考虑切换到std::chrono以获得更准确(和方便)的时间。
标签: c++ time benchmarking