gpt4 book ai didi

c++ - 定时功能 : Double Returning 0 MS

转载 作者:行者123 更新时间:2023-11-28 01:42:31 25 4
gpt4 key购买 nike

我正在为我必须为一个类编写的数据结构编写一个深入的测试程序。我正在尝试计算函数执行所需的时间并将它们存储在数组中以供以后打印。为了仔细检查它是否正常工作,我决定立即打印它,但我发现它不起作用。

这是我获取时间并将它们存储在结构数组中的代码。

void test1(ArrayLinkedBag<ItemType> &bag,TestAnalytics &analytics){
clock_t totalStart;
clock_t incrementalStart;
clock_t stop; //Both timers stop at the same time;
// Start TEST 1
totalStart = clock();
bag.debugPrint();

cout << "Bag Should Be Empty, Checking..." << endl;
incrementalStart = clock();
checkEmpty<ItemType>(bag);
stop = clock();
analytics.test1Times[0] = analytics.addTimes(incrementalStart,stop);
analytics.test1Times[1] = analytics.addTimes(totalStart,stop);
cout << analytics.test1Times[0] << setprecision(5) << "ms" << endl;
std::cout << "Time: "<< setprecision(5) << (stop - totalStart) / (double)(CLOCKS_PER_SEC / 1000) << " ms" << std::endl;
cout << "===========================================" << endl; //So I can find the line easier

}

这是我在数组中进行计算的代码,此函数位于 TestAnalytics 结构中

double addTimes(double start, double stop){
return (stop - start)/ (double)(CLOCKS_PER_SEC/1000);
}

这是我得到的输出的一个片段:

Current Head: -1
Current Size: 0
Cell: 1, Index: 0, Item: 6317568, Next Index: -2
Cell: 2, Index: 1, Item: 4098, Next Index: -2
Cell: 3, Index: 2, Item: 6317544, Next Index: -2
Cell: 4, Index: 3, Item: -683175280, Next Index: -2
Cell: 5, Index: 4, Item: 4201274, Next Index: -2
Cell: 6, Index: 5, Item: 6317536, Next Index: -2
Bag Should Be Empty, Checking...
The Bag Is Empty
0ms
Time: 0 ms
===========================================

我正在尝试根据本网站上的不同帖子计算时间。我在 UNIX 系统上使用 clang 编译器。有没有可能这个数字仍然太小,无法显示在 0 以上?

最佳答案

除非您坚持使用旧的(C++ 11 之前的)编译器/库,否则我会使用 <chrono> 中的函数 header :

template <class ItemType>
void test1(ArrayLinkedBag<ItemType> &bag){
using namespace std::chrono;

auto start = high_resolution_clock::now();
bag.debugPrint();
auto first = high_resolution_clock::now();
checkEmpty(bag);
auto stop = high_resolution_clock::now();

std::cout << " first time: " << duration_cast<microseconds>(first - start).count() << " us\n";
std::cout << "second time: " << duration_cast<microseconds>(stop - start).count() << " us\n";
}

有些部分有点冗长(说得好听),但它仍然工作得相当好。 duration_cast支持低至(至少)nanoseconds 的不同类型,这通常足以对相对较小/较快的代码片段进行计时(尽管不能保证它使用具有纳秒级精度的计时器)。

关于c++ - 定时功能 : Double Returning 0 MS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46597648/

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