본문 바로가기
C & C++/C & C++

시간 연산 관련 함수 모음

by izen8 2012. 11. 28.
반응형


함 수 정리
GetLocalTime : IpSystemTime (현재 로컬 시간을 대입받을 SYSTEMTIME 구조체 사용합니다.) ( 바로가기 )
GetTickCount : 수행 시간을 측정 할때 많이 사용하는 함수( 바로가기 )
GetSystemTime : 현재 Windows System상의 날짜 및 시간을 반환 하는 함수( 바로가기 )
MFC
CTime : MFC에서 사용하는 시간 관련 클래스 단, Millisecond는 없다. ( 바로가기 )
CTime::CurrentTime() : 현재 시간을 구하기
CTimeSpan : MFC에서 사용하는 시간을 연산하는 방법이다. ( 바로가기 )

그외
---------------------------------------------------------------------------------------------
CompareFileTime
DosDateTimeToFileTime
FileTimeToDosDateTime
FileTimeToLocalFileTime
FileTimeToSystemTime
GetFileTime
GetLocalTime
GetSystemTime
GetSystemTimeAdjustment
GetSystemTimeAsFileTime
GetTickCount
GetTimeZoneInformation
LocalFileTimeToFileTime
SetFileTime
SetLocalTime
SetSystemTime
SetSystemTimeAdjustment
SetTimeZoneInformation
SystemTimeToFileTime
SystemTimeToTzSpecificLocalTime
---------------------------------------------------------------------------------------------

  • 시간을 연산하는 것이 말처럼 쉬운 것은 아니라고 생각 합니다. 밀리세컨드를 계산할때는 더욱 골치가 아프고 어떻게 연산을 해야 정확한 값을 가지고 오는지 여러번 테스트를 해야 합니다.
  • 가장 좋은 방법은 API를 활용하여 하나의 프로그램을 만드는 것도 좋지만 기존에 있는 좋은 라이브러리는 적절하게 사용하면 되겠습니다.
  • 그외 시간 관련 함수는 찾아

사용 방법 1. CTime

class CTime
{
public:

// Constructors
static CTime PASCAL GetCurrentTime();

CTime();
CTime(time_t time);
CTime(int nYear, int nMonth, int nDay, int nHour, int nMin, int nSec,
int nDST = -1);
CTime(WORD wDosDate, WORD wDosTime, int nDST = -1);
CTime(const CTime& timeSrc);

CTime(const SYSTEMTIME& sysTime, int nDST = -1);
CTime(const FILETIME& fileTime, int nDST = -1);
const CTime& operator=(const CTime& timeSrc);
const CTime& operator=(time_t t);

// Attributes
struct tm* GetGmtTm(struct tm* ptm = NULL) const;
struct tm* GetLocalTm(struct tm* ptm = NULL) const;
BOOL GetAsSystemTime(SYSTEMTIME& timeDest) const;

time_t GetTime() const;
int GetYear() const;
int GetMonth() const; // month of year (1 = Jan)
int GetDay() const; // day of month
int GetHour() const;
int GetMinute() const;
int GetSecond() const;
int GetDayOfWeek() const; // 1=Sun, 2=Mon, ..., 7=Sat

// Operations
// time math
CTimeSpan operator-(CTime time) const;
CTime operator-(CTimeSpan timeSpan) const;
CTime operator+(CTimeSpan timeSpan) const;
const CTime& operator+=(CTimeSpan timeSpan);
const CTime& operator-=(CTimeSpan timeSpan);
BOOL operator==(CTime time) const;
BOOL operator!=(CTime time) const;
BOOL operator<(CTime time) const;
BOOL operator>(CTime time) const;
BOOL operator<=(CTime time) const;
BOOL operator>=(CTime time) const;

// formatting using "C" strftime
CString Format(LPCTSTR pFormat) const;
CString FormatGmt(LPCTSTR pFormat) const;
CString Format(UINT nFormatID) const;
CString FormatGmt(UINT nFormatID) const;

#ifdef _UNICODE
// for compatibility with MFC 3.x
CString Format(LPCSTR pFormat) const;
CString FormatGmt(LPCSTR pFormat) const;
#endif

// serialization
#ifdef _DEBUG
friend CDumpContext& AFXAPI operator<<(CDumpContext& dc, CTime time);
#endif
friend CArchive& AFXAPI operator<<(CArchive& ar, CTime time);
friend CArchive& AFXAPI operator>>(CArchive& ar, CTime& rtime);

private:
time_t m_time;
};




사용 방법 2. CTimeSpan

class CTimeSpan
{
public:

// Constructors
CTimeSpan();
CTimeSpan(time_t time);
CTimeSpan(LONG lDays, int nHours, int nMins, int nSecs);

CTimeSpan(const CTimeSpan& timeSpanSrc);
const CTimeSpan& operator=(const CTimeSpan& timeSpanSrc);

// Attributes
// extract parts
LONG GetDays() const; // total # of days
LONG GetTotalHours() const;
int GetHours() const;
LONG GetTotalMinutes() const;
int GetMinutes() const;
LONG GetTotalSeconds() const;
int GetSeconds() const;

// Operations
// time math
CTimeSpan operator-(CTimeSpan timeSpan) const;
CTimeSpan operator+(CTimeSpan timeSpan) const;
const CTimeSpan& operator+=(CTimeSpan timeSpan);
const CTimeSpan& operator-=(CTimeSpan timeSpan);
BOOL operator==(CTimeSpan timeSpan) const;
BOOL operator!=(CTimeSpan timeSpan) const;
BOOL operator<(CTimeSpan timeSpan) const;
BOOL operator>(CTimeSpan timeSpan) const;
BOOL operator<=(CTimeSpan timeSpan) const;
BOOL operator>=(CTimeSpan timeSpan) const;

#ifdef _UNICODE
// for compatibility with MFC 3.x
CString Format(LPCSTR pFormat) const;
#endif
CString Format(LPCTSTR pFormat) const;
CString Format(UINT nID) const;

// serialization
#ifdef _DEBUG
friend CDumpContext& AFXAPI operator<<(CDumpContext& dc,CTimeSpan timeSpan);
#endif
friend CArchive& AFXAPI operator<<(CArchive& ar, CTimeSpan timeSpan);
friend CArchive& AFXAPI operator>>(CArchive& ar, CTimeSpan& rtimeSpan);

private:
time_t m_timeSpan;
friend class CTime;
};




사용 방법 3. MFC CTime 클래스 사용


CString CurrentTimeText;
CTime CurTime;

CurTime = CTime::GetCurrentTime(); // 현재 시스템 시각을 구한다.

CurrentTimeText.Format( "현재 날짜 / 시각 : %04d-%02d-%02d / %02d:%02d:%02d",
, CurTime.GetYear()
, CurTime.GetMonth()
, CurTime.GetDay()
, CurTime.GetHour()
, CurTime.GetMinute()
, CurTime.GetSecond()
);



  • 출처 : http://kongmks.cafe24.com/239?TSSESSION=7329c8d8597d2af44015e2b666bb2e6f
  • CString 문자열 클래스에 현재 시간을 대입하여 Format로 각각의 년/월/요 시/분/초 로 정의 할 수 있습니다.

사용 방법 4. Millisecond(밀리세컨드) 현재 시간

SYSTEMTIME cur_time;
GetLocalTime(&cur_time);
CString strPCTime;


strPCTime.Format("%04d%02d%02d%02d%02d%02d%03ld",
cur_time.wYear,
cur_time.wMonth,
cur_time.wDay,
cur_time.wHour,
cur_time.wMinute,
cur_time.wSecond,
cur_time.wMilliseconds); );



  • 출처 : http://blog.naver.com/sanglyn/90047509460
  • CTime 클래스에 밀리세컨드가 없기 때문에 GetLocalTime() API 함수를 이용하여 밀리세컨드 값을 구합니다.


사용 방법 5. GetTickCount 활용 방법

SYSTEMTIME cur_time;

어떤 명령어의 수행시간을 측정하고 싶을때가 있다.
이때 유용하게 사용할수 있는 함수가 GetTickCount()이다.

GetTickCount()함수는 시스템이 시작 된 후 얼마의 시간이 경과했는지를 반환한다. 단위는 밀리세컨드 단위이다. 참고로 경과시간은 DWORD(32비트 값)이므로 최대 49.7일이 지나면 다시 0으로 된다고 한다.

The GetTickCount function retrieves the number of milliseconds that have elapsed since the system was started. It is limited to the resolution of the system timer. To obtain the system timer resolution, use the GetSystemTimeAdjustment function.

DWORD GetTickCount(void);

Parameters : This function has no parameters.
Return values : The return value is the number of milliseconds that have elapsed since the system was started.


#include
#include //GetTickCount()함수 이용을 위해 추가한다.

using namespace std;

void main()
{
long startTime = GetTickCount(); //현재 시각을 저장한다.(시작지점)

for(int i=0; i<100000; i++) //시간 딜레이를 주기 위해 i값을 출력한다.
cout<<

long endTime = GetTickCount(); //현재 시각을 저장한다.(종료지점)
long tickDiff = endTime - startTime; //수행시간 = 종료시각 - 시작시각
long secDiff = tickDiff / 1000 ; //이건 초단위로도 나타내기 위한 것.

cout<<"Start Time : "<<<"ms"<
cout<<"End Time : "<<<"ms"<
cout<<"Tick difference : "<<<"ms"<
cout<<"Second difference : "<<<"s"<
}



  • 출처 : http://dolbbi.com/83
  • 수행시간을 측정하는 방법이며 이것은 49.7일 지나면 0으로 반환 됩니다.

 



1.timeGetTime() 함수? 
윈도우(운영체제)가 시작되어서 지금까지 흐른 시간을 1/1000 초 (milliseconds) 단위로 DWORD형을 리턴하는 함수다.

ex)
만일 윈도우가 뜨고 1분이 지났다면 이 함수는 60,000을 리턴. (부팅 시간은 제외)

2.사용하기
timeGetTime()를 사용하고 싶으면 #include <windows.h> 를 선언해준다.
물론 winmm.lib도 링크시켜야 한다.
방법1. Visual Studio 상단메뉴에서 프로젝트(P) - 속성(P) - 구성속성 - 링커 - 입력으로 들어가 추가종속성에 추가.
방법2. #pragma comment(lib, "winmm.lib") 를 선언
 
3.구현 
이제 timeGetTime()의 세계로 빠져보자!
시간을 초(second)단위로 얻고 싶다면
DWORD t = timeGetTime() / 1000;   또는   DWORD t = timeGetTime() * 0.001f;
위의 방법을 이용하면 된다.
 
예를 들어 0.1초 단위로 실행하고 싶은 함수 AAA()가 있다면 시작과 동시에 한번만 시작시간을 얻고

//시작부분
float m_fStartTime = (float)timeGetTime() * 0.001f;   //초단위로 바꿔줌

//루프 
float NowTime = (float)timeGetTime() * 0.001f;    //초단위로 바꿔줌
 
if( NowTime-m_fStartTime >=  0.1f)   // 여기서 0.1 은 0.1초마다 실행을 의미
{
     //함수실행
     AAA();
}

m_fStartTime = NowTime; 
 
위의 방법을 이용해서 얻은 시간데이터를 시,분,초 단위로 변경할 수 있다.
DWORD Hour = (NowTime/60/60)%60;
DWORD Minute = (NowTime/60)%60;
DWORD Second = NowTime%60;





2.GetTickCount() 함수.

GetTickCount()란?
 
DWORD GetTickCount(VOID);
=> OS부팅할 때부터 지나간 시간을 msec 단위로 돌려주는 함수이다.
 
윈도우즈는 부팅된 후 1초에 1000씩 틱 카운트를 증가시키는데 이 함수를 사용하면 부팅된지 얼마나 경과했는지를 알 수 있다. 카운트는 32비트값이므로 최대 49.7일간의 카운트를 유지할 수 있다. 주로 두 사건 사이의 경과 시간을 측정하기 위한 용도로 사용하며 또는 간단한 애니메이션, 커스텀 커서의 깜박임 주기 조정 등의 용도로도 사용할 수 있다. 이 함수보다 더 정밀한 시간을 측정할 필요가 있을 때는 멀티미디어 타이머나 고해상도 타이머를 사용해야 한다.

예제1) 시간 얻기
//window.h나 afxwin.h  include
 
#include <iostream><?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" /><?xml:namespace prefix = o />
#include <conio.h>
#include <afxwin.h>
#include <cstring>
using std::endl;        using std::cout;
 
#define NUM 1000
 
void main()
{
unsigned long startT = GetTickCount64();
DWORD startTD = GetTickCount64();
cout<< startT <<endl;
cout<<startTD<<endl;

//프로그래밍 루프들~( 시간 소요 )

unsigned long endT = GetTickCount64();
cout<<endT<<endl;
puts("\n");
 
int DletaT = endT- startT;
cout<<DletaT<<endl;
                 
                 
long dSec = (DletaT/1000);
int dMin =(dSec%3600)/60;
int dHour = dSec/3600;;
CString str;
str.Format("Access Time:  %d시간  %d분  %d초", dHour, dMin, dSec%60);
cout<<str<<endl;
 
getch();
}



예제2)GetTickCount()를 사용하여 딜레이 주기

#include <stdio.h>
#include <windows.h>

void main()
{
      while(1)
         {
                 int StartTime;
                 StartTime = GetTickCount();

                 while(GetTickCount() - StartTime >= 1000);
                 {
                 printf ("1초마다 한번씩 실행됩니다\n");
                 }
                 else
                {
                //딜레이를 주는 부분
                 }     
          }
}
 
 
GetTickCount() 함수는 마이크로 초마다 시간값을 받아온다.
즉!!!! StartTime값에 시간값을 저장한 후 새로 값을 받아올때에의 GetTickCount값이 증가하기때문에
GetTickCount() 에서 a를 뺀 값이 1000보다 클때. 즉 1초보다 작을때까진 while-else문을 돌게 된다
즉 그만큼의 딜레이가 발생한다






Date Time Picker 설정


CDateTimeCtrl            pCtrl;        // Control

COleDateTime            m_time;    // Value


1. 초기값 설정 방법 (설정 안하면 현재시간으로 자동 세팅 됨)

COleDateTime timeNow = COleDateTime::GetCurrentTime();    //현재 시간을 가져온다.

pCtrl.SetFormat("HH시 mm분 ss초");                                       //표시 방식 세팅

m_time = COleDateTime(timeNow.GetYear(), timeNow.GetMonth(), timeNow.GetDay(), 14, 59, 00);

VERIFY(pCtrl.SetTime(m_time));                                            //시간을 입력 한다

2. Date Time Picker 에서 값을 가져오기 

VERIFY(pCtrl.GetTime(m_time));                                            //시간 값을 컨트롤에서 가져온다






1. COleDateTime는?

COleDateTime는 유동적으로 변하는 시스템의 날짜와 시간의 값을 얻거나 수정할수 있다.

COleDateTime currentTime;
CString currentDate; //문자열로 저장하기 위한 변수
currentTime = COleDateTime::GetCurrentTime();
currentDate=currentTime.Format("%Y/%m/%d"); // "yyyy/mm/dd" 이런 형식으로 문자열로 출력

Format()함수에 사용할 수 있는 형식지정매개변수

 매개변수 이름 내용 
 %a Abbreviated weekday name 
 %A Full weekday name 
 %b Abbreviated month name 
 %B Full month name 
 %c Date and time representation appropriate for locale 
 %d Day of month as decimal number (01 – 31) 
 %H Hour in 24-hour format (00 – 23) 
 %I Hour in 12-hour format (01 – 12) 
 %j Day of year as decimal number (001 – 366) 
 %m Month as decimal number (01 – 12) 
 %M Minute as decimal number (00 – 59) 
 %p Current locale’s A.M./P.M. indicator for 12-hour clock 
 %S Second as decimal number (00 – 59) 
 %U Week of year as decimal number, with Sunday as first day of week (00 – 53) 
 %w Weekday as decimal number (0 – 6; Sunday is 0) 
 %W Week of year as decimal number, with Monday as first day of week (00 – 53) 
 %x Date representation for current locale 
 %X Time representation for current locale 
 %y Year without century, as decimal number (00 – 99) 
 %Y Year with century, as decimal number
 %z, %Z Time-zone name or abbreviation; no characters if time zone is unknown
 %% Percent Sign

2. 사용 예제

1) 현재 시스템의 년/월/일/시/분/초 를 얻어 오는 예제

  • COleDateTime의 객체를 생성한다.
  • static COleDateTime WINAPI GetCurrentTime( ) throw( ); 현재 날짜/시간을 리턴해 주는 메서드를 이용해 mdiStart를 초기화 해준다.
  • 년/월/일/시/분/초 를 출력해서 값을 확인해 본다.

2) 요일 알아오기.

  • int GetDayOfWeek( ) const throw( ); 메서드를 이용해서 요일을 알아 올수 있다. 보면 알겠지만 반환타입이 int이다. 1~7(일~월)을 리턴한다.

3) 날짜/시간 수정하기


  • int SetDate( int nYear, int nMonth, int nDay ) throw( ); 를 이용해 년/월/일 을 수정 가능하다.
  • int SetTime( int nHour, int nMin, int nSec ) throw( ); 를 이용해 시/분/초 를 수정 가능하다.
  • int SetDateTime( int nYear, int nMonth, int nDay, int nHour, int nMin, int nSec ) throw( ); 를 이용해 SetDate()와 SetTime()메서드에서 설정할수 있는것을 한번에 설정 가능하다.


//////////////////////////////////////////////////////////////////////////////////////////////////
// 2.
CTime, COleDateTime 클래스 생성자 인수로 time_t 형을 파라미터로 받는다. -_-;;;

                time_t longtime;
                //tm pTm;                
                longtime = (time_t)(pevlr->TimeGenerated);  

                //if (localtime_s(&pTm, &longtime)) {
                //    AfxMessageBox(_T("error"));
                // }


                COleDateTime oleTime(longtime);
                CTime ctime(longtime);
                

                INT nYear, nMonth, nDay;
                INT nHour, nMin, nSec;

                
/*
                nYear = oleTime.GetYear();
                nMonth = oleTime.GetMonth();
                nDay = oleTime.GetDay();
                nHour = oleTime.GetHour();
                nMin = oleTime.GetMinute();
                nSec = oleTime.GetSecond();
                */

                nYear = ctime.GetYear();
                nMonth = ctime.GetMonth();
                nMonth = ctime.GetMonth();
                nDay = ctime.GetDay();
                nHour = ctime.GetHour();
                nMin = ctime.GetMinute();
                nSec = ctime.GetSecond();
                TRACE1("%d-", nYear);
                TRACE1("%d-", nMonth);
                TRACE1("%d  ", nDay);
                TRACE1("%d:", nHour);
                TRACE1("%d:", nMin);
                TRACE1("%d\n", nSec);




시스템에서 현재시간을 얻어오는 방법이다.

time_t timer;
struct tm *t;

timer = time(NULL); // 현재 시각을 초 단위로 얻기

t = localtime(&timer); // 초 단위의 시간을 분리하여 구조체에 넣기


tm struct (time.h)

struct tm {
  int tm_sec;   /* Seconds */
  int tm_min;   /* Minutes */
  int tm_hour;  /* Hour (0--23) */
  int tm_mday;  /* Day of month (1--31) */
  int tm_mon;   /* Month (0--11) */
  int tm_year;  /* Year (calendar year minus 1900) */
  int tm_wday;  /* Weekday (0--6; Sunday = 0) */
  int tm_yday;  /* Day of year (0--365) */
  int tm_isdst; /* 0 if daylight savings time is not in effect) */
};

출처 : http://dorio.tistory.com/entry/CC%ED%98%84%EC%9E%AC%EC%8B%9C%EA%B0%84-%EC%96%BB%EA%B8%B0





반응형

댓글