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

trying to store time into array using chrono

我正在测量我编写的算法的时间,并使用 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。因此,您需要获取 raw 值并将其存储或将 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) 不同,您可能会溢出。