微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

为什么我的跑步时钟测量功能给我 0 个时钟?

如何解决为什么我的跑步时钟测量功能给我 0 个时钟?

我在 C 书中做一些练习项目,我被要求编写一个程序,该程序使用 C 库中的时钟函数来测量 qsort 函数对从排序状态反转的数组进行排序所需的时间。所以我写在下面:

/* 
 * Write a program that uses the clock function to measure how long it takes qsort to sort
 * an array of 1000 integers that are originally in reverse order. Run the program for arrays
 * of 10000 and 100000 integers as well.
 */
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define SIZE 10000

int compf(const void *,const void *);

int main(void)
{
    int arr[SIZE];
    clock_t start_clock,end_clock;

    for (int i = 0; i < SIZE; ++i) {
        arr[i] = SIZE - i;
    }

    start_clock = clock();
    qsort(arr,SIZE,sizeof(arr[0]),compf);
    end_clock = clock();
    printf("start_clock: %ld\nend_clock: %ld\n",start_clock,end_clock);
    printf("Measured seconds used: %g\n",(end_clock - start_clock) / (double)CLOCKS_PER_SEC);

    return EXIT_SUCCESS;
}

int compf(const void *p,const void *q)
{
    return *(int *)p - *(int *)q;
}

但是运行程序给了我以下结果:

start_clock: 0          
end_clock: 0         
Measured clock used: 0

我的系统如何使用 0 时钟对数组进行排序?我做错了什么?
我正在使用 mingw-w64 中包含的 GCC,即 x86_64-8.1.0-release-win32-seh-rt_v6-rev0。
此外,我正在编译参数 -g -Wall -Wextra -pedantic -std=c99 -D__USE_MINGW_ANSI_STdiogcc.exe

解决方法

您的问题的 3 个可能答案:

  1. clock_t 是什么?它只是像 int 这样的普通数据类型吗?或者它是某种结构?确保正确使用它的数据类型

  2. 这是在运行什么?例如,如果您的时钟尚未运行,则需要在大多数微控制器上启动它。如果您尝试在不启动的情况下从它拉出,则它始终为 0,因为时钟没有移动

  3. 您的代码是否足够快以至于没有注册?运行实际上需要 0 秒(四舍五入)吗? 1 整秒在编码世界中是很长的时间,你可以在不到一秒的时间内运行数百万行代码。确保您的计时过程可以处理小数字(即您可以注册 1 微秒的计时),或者您的代码运行速度足够慢以注册您的时钟速度

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。