gpt4 book ai didi

c++ - 时间未被计算

转载 作者:行者123 更新时间:2023-11-28 00:20:00 24 4
gpt4 key购买 nike

我想看看哪个访问速度更快,结构体还是元组,所以我写了一个小程序。但是,当它完成运行时,两者记录的时间均为 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(&currentTimeTuple);
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(&currentTimeItem);
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 之间的差值。

最佳答案

time()通常返回自 1970 年 1 月 1 日 UTC(即当前 unix 时间戳)00:00 开始的秒数。因此,根据您的库实现,任何低于 1 秒的内容都可能显示为 0。

您应该更喜欢使用 <chrono> 用于基准测试目的:

chrono::high_resolution_clock::time_point t;
t = high_resolution_clock::now();
// do something to benchmark
chrono::high_resolution_clock::time_point t2 = chrono::high_resolution_clock::now();
cout <<"Exec in ms: "<< chrono::duration_cast<milliseconds>(t2 - t).count() <<endl;

您仍然需要考虑时钟分辨率。例如,对于 windows,它是 15 毫秒,所以如果你接近 15 毫秒左右,甚至更低,你应该增加迭代次数。

关于c++ - 时间未被计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28013741/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com