Search code examples
ctimetime-precision

Set time_t to milliseconds


I have a function and I want the function to stop running once it has been running for a certain number of milliseconds. This function works for seconds but I want to test it for milliseconds. How do I do this? If I set eliminate = 1, it corresponds to 1 second. How do I set eliminate = 5 ms?

Function:

void clsfy_proc(S_SNR_TARGET_SET pSonarTargetSet, unsigned char *target_num, time_t eliminate)
{

    // get timing
    time_t _start = time(NULL);
    time_t _end = _start + eliminate;
    int _eliminate = 0;

    //some code

        time_t start = time(NULL);
        time_t end = start + eliminate;

        for(_tidx = 0; _tidx < pSonarTargetSet[_i].num; _tidx++) {
            // check timing
            time_t _current = time(NULL);
            if (_current > _end) {
                printf("clsfy_proc(1), Eliminate due to timeout\n");
                _eliminate = 1;
                break;
            }

            //some code 

        if (_eliminate == 1)
            break;
    }
    //some code 
}

Solution

  • time_t is an absolute time, represented as the integer number of seconds since the UNIX epoch (midnight GMT, 1 January 1970). It is useful as an unambiguous, easy-to-work-with representation of a point in time.

    clock_t is a relative measurement of time, represented by an integer number of clock ticks since some point in time (possibly the computer's bootup, but no guarantees, as it may roll over quite often). There are CLOCKS_PER_SEC clock ticks per second; the value of this constant can vary between different operating systems. It is sometimes used for timing purposes, but it is not very good at it due to its relatively low resolution.

    One small example for clock_t:

    #include <time.h>
    #include <stdio.h>
    
    int main () {
       clock_t start_t, end_t, total_t;
       int i;
    
       start_t = clock();
       printf("Starting of the program, start_t = %ld\n", start_t);
    
       for(i=0; i< 10000000; i++) { }
    
       end_t = clock();
       printf("End of the big loop, end_t = %ld\n", end_t);
    
       total_t = (double)(end_t - start_t) / CLOCKS_PER_SEC;
       printf("Total time taken by CPU: %f\n", total_t  );
    
       return(0);
    }