c++ - 打印随机数数组的测量时间始终显示为 0 秒

标签 c++ time clock time.h

我的第一篇文章在这里。只是想知道为什么我的秒表总是显示 0 秒或 0 毫秒,无论我的数组中的随机数有多少。我非常感谢你的帮助。 这是我的代码:

#include <iostream>
#include <cstdlib>
#include <time.h>
using namespace std;

double clock_start()
{
    clock_t start = clock();
    return start;
}

void random_number()
{
    int array[10000];
    srand(6);
    cout << "10k Random numbers: ";
    for (int i = 0; i < 10000; i++)
    {
        array[i] = rand() % 99 + 1;
        cout << array[i] << "\n";
    }
}

int main()
{
    setlocale(LC_ALL, "");
    //-------------------------//

    random_number();
    clock_t elapsed = (clock() - clock_start()) / (CLOCKS_PER_SEC / 1000);
    cout << "Stopwatch: " << elapsed << "ms" << " or " << elapsed * 1000 << "s" << endl;

    //-------------------------//
    system("pause > nul");
    return 0;
}

最佳答案

(clock() - clock_start()) 将在眨眼之间进行评估。

所有 clock_start() 所做的就是返回 clock()。 (事实上​​ ,一个好的优化编译器会将 clock_start() 替换为 clock() !)

差异几乎肯定为零。你想要类似的东西吗

clock_t start = clock();
random_number();
clock_t elapsed = (clock() - start) / (CLOCKS_PER_SEC / 1000);

代替?

关于c++ - 打印随机数数组的测量时间始终显示为 0 秒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50800894/

相关文章:

c++ - 在下面的程序中创建了多少个虚表?

c++ - Windows , WinInet C++ API

c - 如何实现 timespec 累加器?

java - System.currentTimeMillis() 在 Windows XP 上不准确?

time - GPS时钟的精度如何?

c - 我在这里做错了什么?程序循环不停

python - 如何在 python 中获得单调持续时间?

c++ - 是否可以动态绑定(bind) operator>?

c++ - 为 map 赋值的最有效方式

c++ - CLOCKS_PER_SEC 的类型