简体   繁体   中英

Why does my running clock measuring function give me 0 clocks?

I'm doing some exercise projects in a C book, and I was asked to write a program that uses clock function in C library to measure how long it takes qsort function to sort an array that's reversed from a sorted state. So I wrote below:

/* 
 * 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;
}

But running the program gives me the results below:

start_clock: 0          
end_clock: 0         
Measured clock used: 0

How can it be my system used 0 clock to sort an array? What am I doing wrong?
I'm using GCC included in mingw-w64 which is x86_64-8.1.0-release-win32-seh-rt_v6-rev0.
Also I'm compiling with arguments -g -Wall -Wextra -pedantic -std=c99 -D__USE_MINGW_ANSI_STDIO given to gcc.exe .

3 possible answers to your issue:

  1. what is clock_t? Is it just a normal data type like int? Or is it some sort of struct? Make sure you are using it correctly for its data type

  2. What is this running on? If your clock isn't already running you need to start it on, for instance, most microcontrollers. If you try pulling from it without starting, it will just be 0 at all times since the clock is not moving

  3. Is your code fast enough that it's not registering? Is it actually taking 0 seconds (rounded down) to run? 1 full second is a very long time in the coding world, you can run millions of lines of code in less than a second. Make sure your timing process can handle small numbers (ie. you can register 1 micro-second of timing), or your code is running slow enough to register on your clock speed

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM