gpt4 book ai didi

c++ - 用时钟计时for循环

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:45:09 25 4
gpt4 key购买 nike

您好,我正在尝试编写一个程序,对 20 个连续数字求和并计算这样做所花费的时间...问题是当我运行该程序时,时间始终为 0...有什么想法吗?

这就是我目前所拥有的...谢谢!

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

int main()
{
int finish = 20;
int start = 1;
int result = 0;

double msecs;
clock_t init, end;

init = clock();

for (int i = start; i <= finish; i++)
{
result += i;
}


end = clock();

cout << ((float)(end - init)) *1000 / (CLOCKS_PER_SEC);

system ("PAUSE");

return 0;
}

最佳答案

无论您使用什么技术来计时,它们都有一定的精度。这执行得如此之快,以至于您的计时器不会在任何时间注册为已经过去。

旁白 #1:使用 high_resolution_clock - 也许这会注册一些非零的东西,可能不会。

旁白 #2:不要将变量命名为 null,在 C++ 中这意味着 0 或空指针

关于c++ - 用时钟计时for循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22872614/

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