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

标签 c++ double

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

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

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/

相关文章:

c++ - 无法使用 this 指针在对象上使用重载的 [] 运算符

java - 为什么 double 可以比 long 存储更多的信息? (JAVA)

c# - 没有小数点的 double 格式

c++ - 在 Ubuntu 中链接 Boost.MPI 和 Boost.Serialization

c++ - 为什么我的矩阵旋转没有通过我学校的单元测试?

c++ - static_cast 可以在 C++ 中抛出异常吗?

c - 从 memcpy 返回到双变量

c++ - 如果 T1 和 T2 有, std::pair<T1,T2> 不应该有简单的默认构造函数吗?

java - 对 double 使用模时性能会下降

计算我的 double 和非 double 的 Java 扫描器类