'time.h'에 해당되는 글 2건

  1. 2010.04.07 system time 측정하기.
  2. 2009.06.30 linux 에서 실행시간 확인 하기..
이전에 post 중에
에 보면 서로 경과 시간을 출력하는 것이 있다.
( gettimeofday 사용)
이번에는 pda 의 응용프로그래밍 때문에 pda 에서도 유사한 코드를 이용, 출력하도록 해 보았다.

을 참조  하였다.


#include <time.h>

static __inline int isLeapYear(int year)
{ return (year % 4) == 0 && ((year % 100) != 0 || (year % 400) == 0); }

static __inline int getCountOfLeapYearFor(int year)
{ return (year / 4) - (year / 100) + (year / 400); }

static __inline int getCountOfDaysFor(int year)
{ return (365 * year) + getCountOfLeapYearFor(year); }

INT64 MC_knlCurrentTime()
{
static const int daysInMonths[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
SYSTEMTIME st[1];
INT64 totalDays;
int month0Based, i;

GetSystemTime(st);


totalDays = st->wDay - 1; // start with 1
month0Based = st->wMonth - 1; // start with 1
for ( i=0; i<month0Based; ++i )
totalDays += daysInMonths[i];
if ( isLeapYear(st->wYear) && month0Based > 1 ) // passed leap month?
++totalDays;
totalDays += getCountOfDaysFor(st->wYear - 1);
return ((totalDays * 24 + st->wHour) * 60 + st->wMinute) * 60 + st->wSecond  - 62135596800i64/*=1970-01-01*/;
}
참고로 코드 수정 부분은 INT64 형으로 바꾼것,
(마지막 함수의 return 형태와 totalDays 변수. )
그리고 ms 단위로 하지 않고 sec 단위로 하기 위하여 마지막 수식을 살짝 바꿨다.

그리고 실제 사용은 다음과 같이 하였다.

INT64 time = MC_knlCurrentTime();

data[size++] = (unsigned char)(time >> 24);
data[size++] = (unsigned char)(time >> 16);
data[size++] = (unsigned char)(time >> 8);
data[size++] = (unsigned char)time;
(작성환경 : VS2008, 실행환경 : PDA. AoM-1250, MIPS processor, WinCE 5.0)

참고로 원 글을 참조하자면, WinCE 5.0 에서는 위 식에서 ms 단위까지의 계산을 지원하지 않는다고 한다. 6.0 부터는 지원한다고 하지만...
(정작 내 폰은 이미 WinCE 6.5 이다. 내 폰(100만원) 보다 안 좋은 180만원짜리 PDA 같으니라고..;; )

그리고 계산상 4byte 이면 32bit 를 표현할 수 있고, 아직 한참 남아돌만큼 쓸 수 있으니 걱정은 하지 않도록 하자.

더불어 이 시간 계산이 맞는지 궁금하면 다음과 같이 linux 에서 컴파일 하여 작동해 보면 확인할 수 있다.

#include <sys/time.h>
#include <iostream.h>

int main()
{
        struct timeval cur;
        gettimeofday(&cur, 0);
cout << "now : " << cur.tv_sec<<endl;
        return 0;
}
참~~ 쉽죠잉?
(환경 : 컴파일러는 다음 참조하자. 뭐 별꺼 있겠냐만. ;;;
yoons@yoons-desktop:~$ g++ -v
Using built-in specs.
Target: i486-linux-gnu
Configured with: ../src/configure -v --enable-languages=c,c++,fortran,objc,obj-c++,treelang --prefix=/usr --enable-shared --with-system-zlib --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --enable-nls --with-gxx-include-dir=/usr/include/c++/4.2 --program-suffix=-4.2 --enable-clocale=gnu --enable-libstdcxx-debug --enable-objc-gc --enable-mpfr --enable-targets=all --enable-checking=release --build=i486-linux-gnu --host=i486-linux-gnu --target=i486-linux-gnu
Thread model: posix
gcc version 4.2.4 (Ubuntu 4.2.4-1ubuntu4)
yoons@yoons-desktop:~$
Posted by Yoons...
,
linux 에서 시간을 확인할 것이 필요해서 뭐 좀 찾아봤다.
linux 에서는 time.h 를 이용하여 시간 관련된 구조체를 선언 후 시스템에서 시간을 끌어와 사용 가능하다.
시간관련 구조체를 선언 후, gettimeofday라는 것을 호출하면 시간 구조체에 시간값을 가져오게 된다.

아래는 joinc 위키 에서 찾은 gettimeofday 관련된 예제 함수.

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

int main()
{
    struct timeval mytime;

    // 현재 시간을 얻어온다.
    gettimeofday(&mytime, NULL);
    printf("%ld:%ld\n", mytime.tv_sec, mytime.tv_usec);

    // 시간을 1시간 뒤로 되돌려서 설정한다.
    mytime.tv_sec -= 3600;
    settimeofday(&mytime, NULL);
    return 0;
}
그러면 timeval 구조체에 tv_sec, tv_usec 안에 초, u초 가 들어오게 된다.
일일이 뺄 수도 있지만,
친절한 메크로씨는 이미 다 선언이 되어 있다.

위에 시간 구조체를 쓰기 위한 헤더들을 선언한다면
그 안에 되어 있으므로 아래 매크로를 쓰는것은 덤. ㅋㅋㅋ
( KLDP 에서 찾았다. )
 
# define timeradd(a, b, result)                           \
  do {                                        \
    (result)->tv_sec = (a)->tv_sec + (b)->tv_sec;                 \
    (result)->tv_usec = (a)->tv_usec + (b)->tv_usec;                  \
    if ((result)->tv_usec >= 1000000)                         \
      {                                       \
    ++(result)->tv_sec;                           \
    (result)->tv_usec -= 1000000;                         \
      }                                       \
  } while (0)
# define timersub(a, b, result)                           \
  do {                                        \
    (result)->tv_sec = (a)->tv_sec - (b)->tv_sec;                 \
    (result)->tv_usec = (a)->tv_usec - (b)->tv_usec;                  \
    if ((result)->tv_usec < 0) {                          \
      --(result)->tv_sec;                             \
      (result)->tv_usec += 1000000;                       \
    }                                         \
  } while (0)    

사용만 하면 되는거다.

// 헤더선언,
// 구조체 선언

gettimeofday(&mytime1, NULL);
// 실행코드
gettimeofday(&mytime2, NULL);
timersub(&mytime2, &mytime1, &result);

이런식으로 그냥 쓰면 되는거다. ㅋㅋ

'Study.. > Programming' 카테고리의 다른 글

문제가 있을 때는...  (0) 2009.08.06
IAR 에서 printf 사용하기.  (0) 2009.06.30
race condition ( thread, mutex, semaphore)  (0) 2009.05.29
no newline at end of file  (0) 2009.05.29
Javascript 계산기  (0) 2008.10.28
Posted by Yoons...
,