Calculate execution time when sleep() is used

后端 未结 5 1802
难免孤独
难免孤独 2021-01-23 11:30

I am trying to read data from the ADC in the Beagle Bone, running Angstrom Linux distribution. I need to use a delay mechanism like sleep(), to only read samples at

5条回答
  •  死守一世寂寞
    2021-01-23 12:08

    I use MACRO to print the elapse time.

    #include 
    #include 
    #include 
    #define ELPS_TIME(func_name) do { \
        struct timeval tval_before, tval_after, tval_result; \
        gettimeofday(&tval_before, NULL); \
        func_name; \
        gettimeofday(&tval_after, NULL); \
        timersub(&tval_after, &tval_before, &tval_result); \
        printf("Time elapsed: %ld.%06ld seconds\n", \
            (long int)tval_result.tv_sec, \
            (long int)tval_result.tv_usec); } while(0)
    
    static void test_func1() {
        printf("%s:", __FUNCTION__);
        sleep(1);
    }
    
    static void test_func2() {
        printf("%s:", __FUNCTION__);
        sleep(2);
    }
    
    int main() {
        ELPS_TIME(test_func1()); //calling test_func1 
        ELPS_TIME(test_func2()); //calling test_func2
        return 0;
    }
    

    Output:

    test_func1:Time elapsed: 1.000103 seconds                                                                             
    test_func2:Time elapsed: 2.000974 seconds 
    

提交回复
热议问题