C++ time, clock 시간 측정, 현재 시간 구하기

Notepad96

·

2020. 11. 18. 21:32

300x250

 

 

 


1. clock_t, time_t

 

시간 관련 함수들은 ctime (time.h) 라이브러리의 존재 한다.

 

 

 

clock 함수는 프로그램 시간을 읽어와 이를 이용하여 시간을 측정할 수 있으며

 

 

 

time은 현재 시간을 읽어와 현재 날짜와 시간을 표시할 수도 있다.

 

 

 

또한 년도, 월, 시, 분 과 같은 값들을 묶어 저장, 관리 할 수 있도록 구조체도 지원한다.

 

 

 

 


2. 코 드

환경 : Visual studio 2019

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <ctime>
using namespace std;

int main() {
    clock_t start = clock();
    for (int i = 0; i < 50000; i++) {
        for (int k = 0; k < 50000; k++);
    }
    clock_t end = clock();
    
    cout << "걸린 시간 : \n";
    cout << difftime(end, start) / 1000.0 << " 초\n";
    cout << (double)(end - start) / 1000.0 <<  " 초\n";
    cout << (double)(end - start) / CLOCKS_PER_SEC << " 초\n";
    
    cout << "============================================\n";


    time_t temp;
    struct tm* timeinfo;

    time(&temp);
    timeinfo = localtime(&temp);
    
    cout << "현재 시간 : " << asctime(timeinfo);
    cout << "현재 년도 : " << 1900 + timeinfo->tm_year << "\n";
    cout << "현재 월 : " << 1 + timeinfo->tm_mon  << "\n";
    cout << "현재 일 : " << timeinfo->tm_mday << "\n";

    return 0;
}
 
결과

 

 
 - clock_t 타입의 start와 end 변수를 선언한 후 clock()로 초기화 한다.
 
 
이후 두 시간의 차를 구하면 start와 end 사이의 시간을 측정 할 수 있다.
 
 
여기서 시간 차를 구하기 위해서 end - start를 해주거나 difftime() 함수를 사용할 수 있다.
 
 
 
 
마지막으로 구한 시간차를 우리가 흔히 사용하는 초 단위로 바꾸기 위하여
 
1000.0 = CLOCKS_PER_SEC 으로 나누어주면 초 단위의 시간을 얻을 수 있다.
 
 
 
 
 
 
 - struct tm*날짜, 시간을 저장하기 위한 구조체이다.
 
 
localtime 함수를 사용함으로써 time 함수로 현재 시간을 구한 time_t 타입을 tm 타입으로 변환한다.
 
 
 
 
tm 구조체에서는 tm_year 년도, tm_mon 월 처럼 각 값에 접근할 수도 있다.
 
 

또한, 년도는 1900년도 시작이거나 월은 0~11까지이거나 요일(tm_wday)은 0~6처럼 시작 기준이 다른 것은 사용할 때 주의하여야 한다.

 
 
 
 
 

3. 참 조

 

 

localtime - C++ Reference

function localtime struct tm * localtime (const time_t * timer); Convert time_t to tm as local time Uses the value pointed by timer to fill a tm structure with the values that represent the corresponding time, expressed for the local timezone. Para

www.cplusplus.com

 

 

struct tm - C++ Reference

tm_isdstintDaylight Saving Time flag

www.cplusplus.com

 

300x250

'C++ > STL' 카테고리의 다른 글

C++ isupper, islower, isdigit - 문자 대소문자, 숫자 판별  (0) 2020.11.20
C++ min, max 함수  (0) 2020.11.19
C++ 원소 삭제하기 remove  (0) 2020.11.18
C++ 값 회전하기 rotate  (0) 2020.11.18
C++ 거꾸로 뒤집기 reverse  (0) 2020.11.17