尝试使用chrono将时间存储到数组中

trying to store time into array using chrono

本文关键字:存储 数组 时间 chrono      更新时间:2023-10-16

我正在测量我编写的算法的时间,并使用std::chrono以微秒为单位进行测量。然而,我也在尝试将这些经过的值存储到一个数组中,我不确定如何存储。我试过这个(我的数组是int类型)

 std::chrono::duration_cast<std::chrono::microseconds>(end - start);

 time_insertion_sort[i][j] = elapsed;

我得到以下错误:

error: cannot convert 'std::chrono::duration<long int, std::ratio<1l,
       1000000l> >' to 'int' in assignment
time_insertion_sort[i][j] = elapsed; 

我想,如果我将数组声明为long类型,也许它会起作用,但它仍然不起作用。有人能帮我吗?

当您声明您的数组的类型为int时,错误是它无法将std::duration类型转换为int。因此,您需要获取原始值并将其存储或将std::duration类型存储在数组中。

auto elapsed = std::chrono::duration_cast<std::chrono::microseconds>(end - start);
// You should be able to store this raw value.
auto rawValue = elapsed.count();

注意count函数返回的类型是std::duration的表示类型。您的错误消息指示表示类型为long int,因此,如果sizeof(int)sizeof(long)不同,则会发生溢出。