1. gettimeofday

#include <sys/time.h>

#include <unistd.h>


int gettimeofday(struct timeval *tv, struct timezone *tz);

int settimeofday(const struct timeval *tv, const struct timezone *tz);


struct timeval {

    long tv_sec;

    long tv_usec;

}


struct timezone {

    long tz_minuteswest;

    long tz_dsttime;

}


ex) gettimeofday

#include <stdio.h>
#include <unistd.h>
#include <sys/time.h>

int main( int argc, char ** argv )
{
    struct timeval tmstart, tmend;
    unsigned long elapsed;

    for(;;)
    {
        gettimeofday(&tmstart, NULL);
        usleep( 20000 );

        gettimeofday(&tmend, NULL);
        elapsed = (tmend.tv_sec - tmstart.tv_sec)*1000000 + tmend.tv_usec - tmstart.tv_usec;

        printf("elapsed time : %ld\n", elapsed);

       

        // 만약 시간을 뒤로 1시간 돌리고 싶다면

        tmend.tv_sec - 3600;

        settimeofday(&tmend, NULL);
    }

return 0;
}


2. clock_gettime

nanoseconds 까지 측정 가능한 함수 이다.

struct timespec {

    time_t tv_sec;     /* seconds */

    long tv_nsec;     /* nanoseconds */


ex) clock_gettime

컴파일시 -lrt 옵션을 넣어서 해당 library를 링크 시켜줘야 한다.

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

int main( int argc, char ** argv )
{

        const unsigned long long nano = 1000000000;
        unsigned long long t1, t2;

        struct timespec tm;

        for(;;)
        {

                clock_gettime( CLOCK_REALTIME, &tm );
                t1 = tm.tv_nsec + tm.tv_sec * nano;

                usleep( 20000 );

                clock_gettime( CLOCK_REALTIME, &tm );
                t2 = tm.tv_nsec + tm.tv_sec * nano;

                printf( "delay: %ld\n", ( t2 - t1 ) / 1000 );
        }

        return 0;

}


아래와 같이 함수를 만들어 사용하면 ms 시간을 얻어 편리하게 사용할 수 있을 것으로 보인다.

static long getTime(void)
{
    struct timeval  now;
    gettimeofday(&now, NULL);
    return (long)(now.tv_sec*1000 + now.tv_usec/1000);
}


static long _getTime(void)
{
    struct timespec now;
    clock_gettime(CLOCK_MONOTONIC, &now);
    return now.tv_sec*1000000 + now.tv_nsec/1000;
}



'Embedded Linux > Tip' 카테고리의 다른 글

dpkg를 이용한 package 정보를 알고 싶을 때  (0) 2014.08.14
[vim] Copy&Paste  (0) 2014.04.23
Target board에 대한 Toolchain 선택  (1) 2013.12.04
Posted by 깍수
,