C `clock()` 函数只返回一个零

2023-06-30C/C++开发问题
5

本文介绍了C `clock()` 函数只返回一个零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

C clock() 函数只返回零.我尝试使用不同的类型,但没有任何改进......这是一种以高精度测量时间的好方法吗?

#include #include int main(){clock_t 开始,结束;双 cpu_time_used;字符 [32];开始 = 时钟();printf("
睡眠 3 秒...

");睡眠(3);结束 = 时钟();cpu_time_used = ((double)(end - start))/((double)CLOCKS_PER_SEC);printf("start = %.20f
end = %.20f
", start, end);printf("delta = %.20f
", ((double) (end - start)));printf("cpu_time_used = %.15f
", cpu_time_used);printf("CLOCKS_PER_SEC = %i

", CLOCKS_PER_SEC);返回0;}

<块引用>

睡眠3秒...开始 = 0.00000000000000000000结束 = 0.00000000000000000000增量 = 0.00000000000000000000cpu_time_used = 0.000000000000000CLOCKS_PER_SEC = 1000000

平台:Intel 32 位,RedHat Linux,gcc 3.4.6

解决方案

clock() 报告 CPU 使用时间.sleep() 不使用任何 CPU 时间.所以你的结果可能完全正确,只是不是你想要的.

The C clock() function just returns me a zero. I tried using different types, with no improvement... Is this a good way to measure time with good precision?

#include <time.h>
#include <stdio.h>

int main()
{
    clock_t start, end;
    double cpu_time_used;

    char s[32];

    start = clock();

    printf("
Sleeping 3 seconds...

");
    sleep(3);

    end = clock();

    cpu_time_used = ((double)(end - start)) / ((double)CLOCKS_PER_SEC);

    printf("start = %.20f
end   = %.20f
", start, end);
    printf("delta = %.20f
", ((double) (end - start)));
    printf("cpu_time_used  = %.15f
", cpu_time_used);
    printf("CLOCKS_PER_SEC = %i

", CLOCKS_PER_SEC);

    return 0;
}

Sleeping 3 seconds...

start = 0.00000000000000000000
end   = 0.00000000000000000000
delta = 0.00000000000000000000
cpu_time_used  = 0.000000000000000
CLOCKS_PER_SEC = 1000000

Platform: Intel 32 bit, RedHat Linux, gcc 3.4.6

解决方案

clock() reports CPU time used. sleep() doesn't use any CPU time. So your result is probably exactly correct, just not what you want.

这篇关于C `clock()` 函数只返回一个零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&amp;()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6