본문 바로가기
VisualStudio.C++.C#/C . C++

C++ std::chrono, time_point, duration, system_clock, steady_clock 고정밀 시각, 시간.

by 리치굿맨 2016. 2. 20.

 

 

개요

  고정밀 시각, 시간측정용  std::chrono 는 "C++11" 이후 도입, Visual C++ 2012 이후 도입.


용어. 
시각 : time point.
시간 : time interval, 2개 시각의 간격.


특징
- 고정밀(최소 시간단위 : 나노초), 편리기능 함수들.
- 주요 클래스 : duration, time_point
- 주요구조체 : system_clock, steady_clock
- steady_clock 특징 
Visual C++ 에서는 내부적으로 QueryPerformanceCounter 로 구현되어있음.
monotonic. 늦게 호출된 now() 가 먼저 호출된 now() 이상의 값(같거나 더 큰 값)이 나온다는 의미.




헤더파일 #include <chrono>


더보기
<chrono>

Include the standard header <chrono> to define classes and functions that represent and manipulate time durations and time instants.
(Visual Studio 2015:) The implementation of steady_clock has changed to meet the C++ Standard requirements for steadiness and monotonicity. steady_clock is now based on QueryPerformanceCounter() and high_resolution_clock is now a typedef for steady_clock. As a result, in Visual C++ steady_clock::time_point is now a typedef for chrono::time_point<steady_clock>; however, this is not necessarily the case for other implementations.
C++
복사
#include <chrono>


Hh874757.collapse_all(ko-kr,VS.140).gifLiterals

Literals in the <chrono> header are members of the literals::chrono_literals inline namespace. For more information, see chrono literals.
 
operator "" h(unsigned long long Val) operator "" h(long double Val) Specifies that the value represents hours.
operator "" min(unsigned long long Val) operator "" min(long double Val) Specifies that the value represents minutes.
operator "" s(unsigned long long Val)operator "" s(long double Val) Specifies that the value represents seconds.
operator "" ms(unsigned long long Val)operator "" ms(long double Val) Specifies that the value represents milliseconds.
operator "" us(unsigned long long Val)operator "" us(long double Val) Specifies that the value represents microseconds.
operator "" ns(unsigned long long Val)operator "" ns(long double Val) Specifies that the value represents nanoseconds.

Hh874757.collapse_all(ko-kr,VS.140).gifClasses

 
Name Description
duration Class Describes a type that holds a time interval.
time_point Class Describes a type that represents a point in time.

Hh874757.collapse_all(ko-kr,VS.140).gifStructs

 
Name Description
common_type Structure Describes specializations of template class common_type for instantiations of duration and time_point.
duration_values Structure Provides specific values for the duration template parameter Rep.
steady_clock struct Represents a steady clock.
system_clock Structure Represents a clock type that is based on the real-time clock of the system.
treat_as_floating_point Structure Specifies whether a type can be treated as a floating-point type.

Hh874757.collapse_all(ko-kr,VS.140).gifFunctions

 
Name Description
duration_cast Function Casts a duration object to a specified type.
time_point_cast Function Casts a time_point object to a specified type.

Hh874757.collapse_all(ko-kr,VS.140).gifOperators

 
Name Description
operator- Operator (STL) Operator for subtraction or negation of duration and time_point objects.
operator!= Operator (STL) Inequality operator that is used with duration or time_point objects.
operator modulo (STL) Operator for modulo operations on duration objects.
operator* Operator (STL) Multiplication operator for duration objects.
operator/ Operator (STL) Division operator for duration objects.
operator+ Operator (STL) Adds duration and time_point objects.
operator< Operator (STL) Determines whether one duration or time_point object is less than another duration or time_point object.
operator<= Operator (STL) Determines whether one duration or time_point object is less than or equal to another duration or time_point object.
operator== Operator (STL) Determines whether two duration objects represent time intervals that have the same length, or whether two time_point objects represent the same point in time.
operator> Operator (STL) Determines whether one duration or time_point object is greater than another duration or time_point object.
operator>= Operator (STL) Determines whether one duration or time_point object is greater than or equal to another duration or time_point object.

Hh874757.collapse_all(ko-kr,VS.140).gifPredefined Duration Types

For more information about ratio types that are used in the following typedefs, see <ratio>.
 
Typedef Description
typedef duration<long long, nano> nanoseconds; Synonym for a duration type that has a tick period of one nanosecond.
typedef duration<long long, micro> microseconds; Synonym for a duration type that has a tick period of one microsecond.
typedef duration<long long, milli> milliseconds; Synonym for a duration type that has a tick period of one millisecond.
typedef duration<long long> seconds; Synonym for a duration type that has a tick period of one second.
typedef duration<int, ratio<60> > minutes; Synonym for a duration type that has a tick period of one minute.
typedef duration<int, ratio<3600> > hours; Synonym for a duration type that has a tick period of one hour.

Hh874757.collapse_all(ko-kr,VS.140).gifLiterals

(C++11)The <chrono> header defines the following user-defined literals that you can use for greater convenience, type-safety and maintainability of your code. These literals are defined in the literals::chrono_literals inline namespace and are in scope when std::chrono is in scope.
 
Literal Description
chrono::hours operator "" h(unsigned long long Val) Specifies hours as an integral value.
chrono::duration<double, ratio<3600> > operator "" h(long double Val) Specifies hours as a floating-point value.
chrono::minutes (operator "" min)(unsigned long long Val) Specifies minutes as an integral value.
chrono::duration<double, ratio<60> > (operator "" min)( long double Val) Specifies minutes as a floating-point value.
chrono::seconds operator "" s(unsigned long long Val) Specifies minutes as an integral value.
chrono::duration<double> operator "" s(long double Val) Specifies seconds as a floating-point value.
chrono::milliseconds operator "" ms(unsigned long long Val) Specifies milliseconds as an integral value.
chrono::duration<double, milli> operator "" ms(long double Val) Specifies milliseconds as a floating-point value.
chrono::microseconds operator "" us(unsigned long long Val) Specifies microseconds as an integral value.
chrono::duration<double, micro> operator "" us(long double Val) Specifies microseconds as a floating-point value.
chrono::nanoseconds operator "" ns(unsigned long long Val) Specifies nanoseconds as an integral value.
chrono::duration<double, nano> operator "" ns(long double Val) Specifies nanoseconds as a floating-point value.




from : MSDN


더보기
duration Class




Describes a type that holds a time interval, which is an elapsed time between two time points.
 
복사
template< class Rep, class Period = ratio<1> > class duration; template< class Rep, class Period > class duration; template< class Rep, class Period1, class Period2 > class duration <duration<Rep, Period1>, Period2>;
The template argument Rep describes the type that is used to hold the number of clock ticks in the interval. The template argument Period is an instantiation of ratio that describes the size of the interval that each tick represents.

Hh874624.collapse_all(ko-kr,VS.140).gifPublic Typedefs

 
Name Description
duration::period Typedef Represents a synonym for the template parameter Period.
duration::rep Typedef Represents a synonym for the template parameter Rep.

Hh874624.collapse_all(ko-kr,VS.140).gifPublic Constructors

 
Name Description
duration::duration Constructor Constructs a duration object.

Hh874624.collapse_all(ko-kr,VS.140).gifPublic Methods

 
Name Description
duration::count Method Returns the number of clock ticks in the time interval.
duration::max Method Static. Returns the maximum allowable value of template parameter Ref.
duration::min Method Static. Returns the lowest allowable value of template parameter Ref.
duration::zero Method Static. In effect, returns Rep(0).

Hh874624.collapse_all(ko-kr,VS.140).gifPublic Operators

 
Name Description
duration::operator- Operator Returns a copy of the duration object together with a negated tick count.
duration::operator-- Operator Decrements the stored tick count.
duration::operator= Operator Reduces the stored tick count modulo a specified value.
duration::operator*= Operator Multiplies the stored tick count by a specified value.
duration::operator/= Operator Divides the stored tick count by the tick count of a specified duration object.
duration::operator+ Operator Returns *this.
duration::operator++ Operator Increments the stored tick count.
duration::operator+= Operator Adds the tick count of a specified duration object to the stored tick count.
duration::operator-= Operator Subtracts the tick count of a specified duration object from the stored tick count.
Header: chrono
Namespace: std::chrono



더보기
time_point Class

A time_point describes a type that represents a point in time. It holds an object of type duration that stores the elapsed time since the epoch that is represented by the template argument Clock.
 
복사
template< class Clock, class Duration = typename Clock::duration > class time_point;

Hh874638.collapse_all(ko-kr,VS.140).gifPublic Typedefs

 
Name Description
time_point::clock Synonym for the template parameter Clock.
time_point::duration Synonym for the template parameter Duration.
time_point::period Synonym for the nested type name duration::period.
time_point::rep Synonym for the nested type name duration::rep.

Hh874638.collapse_all(ko-kr,VS.140).gifPublic Constructors

 
Name Description
time_point::time_point Constructor Constructs a time_point object.

Hh874638.collapse_all(ko-kr,VS.140).gifPublic Methods

 
Name Description
time_point::max Method Specifies the upper limit for time_point::ref.
time_point::min Method Specifies the lower limit for time_point::ref.
time_point::time_since_epoch Method Returns the stored duration value.

Hh874638.collapse_all(ko-kr,VS.140).gifPublic Operators

 
Name Description
time_point::operator+= Operator Adds a specified value to the stored duration.
time_point::operator-= Operator Subtracts a specified value from the stored duration.
Header: chrono
Namespace: std::chrono



더보기
system_clock Struct


Represents a clock type that is based on the real-time clock of the system.
 
복사
struct system_clock;
A clock type is used to obtain the current time as UTC. The type embodies an instantiation of duration and the class template time_point, and defines a static member function now() that returns the time.
A clock is monotonic if the value that is returned by a first call to now() is always less than or equal to the value that is returned by a subsequent call to now().
A clock is steady if it is monotonic and if the time between clock ticks is constant.
In this implementation, a system_clock is synonymous with a high_resolution_clock.

Hh874826.collapse_all(ko-kr,VS.140).gifPublic Typedefs

 
Name Description
system_clock::duration A synonym for duration<rep, period>.
system_clock::period A synonym for the type that is used to represent the tick period in the contained instantiation of duration.
system_clock::rep A synonym for the type that is used to represent the number of clock ticks in the contained instantiation of duration.
system_clock::time_point A synonym for time_point<Clock, duration>, where Clock is a synonym for either the clock type itself or another clock type that is based on the same epoch and has the same nested duration type.

Hh874826.collapse_all(ko-kr,VS.140).gifPublic Methods

 
Name Description
system_clock::from_time_t Method Static. Returns a time_point that most closely approximates a specified time.
system_clock::now Method Static. Returns the current time.
system_clock::to_time_t Method Static. Returns a time_t object that most closely approximates a specified time_point.

Hh874826.collapse_all(ko-kr,VS.140).gifPublic Constants

 
Name Description
system_clock::is_monotonic Constant Specifies whether the clock type is monotonic.
system_clock::is_steady Constant Specifies whether the clock type is steady.
Header: chrono
Namespace: std::chrono



더보기
steady_clock Struct

 Represents a steady clock.
 
복사
struct steady_clock;
On Windows, steady_clock wraps the QueryPerformanceCounter function.
A clock is monotonic if the value that is returned by a first call to now() is always less than or equal to the value that is returned by a subsequent call to now().
A clock is steady if it is monotonic and if the time between clock ticks is constant.
High_resolution_clock is a typdef for steady_clock.


 
Function Description
now Returns the current time as a time_point value.
 
Name Description
system_clock::is_steady Holds true. A steady_clock is steady.
Header: chrono
Namespace: std::chrono





cpp reference 사이트의


chrono : http://en.cppreference.com/w/cpp/header/chrono
time_point : http://en.cppreference.com/w/cpp/chrono/time_point
duration  : http://en.cppreference.com/w/cpp/chrono/duration 

 

 

 

 

코드예-1

 

현재시각 구하기. (epoch이후의 경과시간)


std::chrono::system_clock::time_point tp_Now = std::chrono::system_clock::now();  
std::chrono::system_clock::duration duEpoch = tp_Now.time_since_epoch();
int64_t TimeIntervalEpoch_64 = std::chrono::duration_cast<std::chrono::nanoseconds>duEpoch.count();


설명.
1.  now() 함수 호출한 시점의 "시각"이  자료형 time_point 변수 tp_Now 에 저장된다. 
2. 상기1에서 "시각"이라함은 epoch(UTC 1970년 1월 1일 0시0분0초 시점) 이후 now 호출한 시점까지의 나노초 단위의 경과시간.
3. 상기2의 epoch이후의 경과시간은 time_point 의 멤버 함수 time_since_epoch() 호출하여 duration 형 변수 duEpoch로 받았다.
4. duEpoch.count() 함수 호출로 64비트 정수형 변수 TimeIntervalEpoch_64 으로 받았다. 


주의사항:  nanoseconds 로 명시적 형변환 해야만 정확한 값을 받을 수 있음. nanoseconds 로 형변환 하지 않은 경우엔 반환값이 나노도 아니고, 마이크로 초도 아닌 나노초 기준 100으로 나눈값이 반환됨.
nanoseconds 로 명시적 형변환 한 경우 : epoch 이후 경과한 정확한 나노초 : 1456136176997090600 
명시적 형변환 없이 duEpoch.count(); 로 그냥 받은 경우 : 14561361769970906  상기 대비 100으로 나눈값임.




코드의 특정 처리구간 시간격 구하기.


1
2
3
4
5
6
7
8
9
10
11
12
13
std::chrono::steady_clock::time_point tp_start = std::chrono::steady_clock::now();  
 
... 이것저것 처리구간.
 
std::chrono::steady_clock::time_point tp_end = std::chrono::steady_clock::now();  
 
 
std::chrono::nanoseconds diff_nano = tp_end - tp_start; // 나노(10^-9)초 단위로 차이 구한다.
 
std::chrono::microseconds diff_micro = duration_cast<microseconds>(tp_end - tp_start); // 마이크로(10^-6)초 단위로 차이 구한다.
 
std::chrono::miliseconds diff_mili = duration_cast<miliseconds>(tp_end - tp_start); // 밀리(10^-3)초 단위로 차이 구한다.
 



 

 

 

 

코드예-2. 당일 0시 이후 현재까지 경과시간 나노초 단위로 받기.

 
 
아래 코드에 사용된 std::time_t, std:tm 상세 보기 : http://igotit.tistory.com/673
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
        std::time_t tNow = std::time(NULL); // epoch(1970년 1월1일0시0분0초) 이후 초단위.
 
    std::tm tmYMDHMS; // 현재일자의 0시0분0초 기록할 변수.
 
    tmYMDHMS.tm_year = std::localtime(&tNow)->tm_year;
    tmYMDHMS.tm_mon = std::localtime(&tNow)->tm_mon;
    tmYMDHMS.tm_mday = std::localtime(&tNow)->tm_mday;
    tmYMDHMS.tm_hour = 0; 
    tmYMDHMS.tm_min = 0;
    tmYMDHMS.tm_sec = 0; 
 
    std::time_t theDay000 = std::mktime(&tmYMDHMS); //tmYMDHMS를 time_t 형식으로 변경. 
 
    // time_point 형으로 당일0시0분0초 받음. 
    std::chrono::system_clock::time_point tpDay000 = std::chrono::system_clock::from_time_t(theDay000); 
    
    // time_point 형으로 현재 시각(epoch 이후 경과시간)받음. 
    std::chrono::system_clock::time_point tpNow = std::chrono::system_clock::now();
 
    std::cout << "오늘 0시 이후 경과      시 : "
        << std::chrono::duration_cast<std::chrono::hours>(tpNow - tpDay000).count() << '\n';
 
    std::cout << "오늘 0시 이후 경과      분 : "
        << std::chrono::duration_cast<std::chrono::minutes>(tpNow - tpDay000).count() << '\n';
 
    std::cout << "오늘 0시 이후 경과      초 : "
        << std::chrono::duration_cast<std::chrono::seconds>(tpNow - tpDay000).count() << '\n';
 
    std::cout << "오늘 0시 이후 경과 밀리 초 : "
        << std::chrono::duration_cast<std::chrono::milliseconds>(tpNow - tpDay000).count() << '\n';
 
    std::cout << "오늘 0시 이후 경과 마이크로초 : " 
        << std::chrono::duration_cast<std::chrono::microseconds>(tpNow - tpDay000).count() << '\n';
 
    std::cout << "오늘 0시 이후 경과 나노  초 : "
        << std::chrono::duration_cast<std::chrono::nanoseconds>(tpNow - tpDay000).count() << '\n';
 
실행결과.
오늘 0시 이후 경과      시 : 23
오늘 0시 이후 경과      분 : 1415
오늘 0시 이후 경과      초 : 84957
오늘 0시 이후 경과 밀리 초 : 84957784
오늘 0시 이후 경과 마이크로초 : 84957784079
오늘 0시 이후 경과 나노  초 : 84957784079500 

 

 

 

 

 

코드예-3. 실수형으로 받기.

 
상기 코드예-2의 마지막에 아래 코드 추가.
 
1
2
3
4
5
6
7
8
9
10
    using FpFloatMilliseconds = std::chrono::duration<float, std::chrono::milliseconds::period>;
    using FpDoubleMilliseconds = std::chrono::duration<double, std::chrono::milliseconds::period>;
 
    float f_ms = FpFloatMilliseconds(tpNow - tpDay000).count();
    double d_ms = FpDoubleMilliseconds(tpNow - tpDay000).count();
 
    printf("float 밀리초 :%f\n", f_ms);
    printf("double 밀리초 :%f\n", d_ms);
 
 
 
실행결과.
오늘 0시 이후 경과      시 : 0
오늘 0시 이후 경과      분 : 26
오늘 0시 이후 경과      초 : 1570
오늘 0시 이후 경과 밀리 초 : 1570301
오늘 0시 이후 경과 마이크로초 : 1570301927
오늘 0시 이후 경과 나노  초 : 1570301927700
float 밀리초 :1570302.000000
double 밀리초 :1570301.927700

 

 

 

 

 

 

연관 

 

 

 

std::time_t, std::tm

개요 std::time_t epoch (1970년 1월 1일 0시0분0초)이후 현재까지의 초단위 경과시간. std::tm 년,월,일,시,분,초 분리 처리시 용이. 헤더파일 #include 코드예-1. 현재시간 받고 년월일시분초 분리. std::time_t..

igotit.tistory.com

 

 

 

상위정리

Visual Studio/VC++/C/C# 활용정리 -> http://igotit.tistory.com/11

 

Visual Studio , Visual C++ 활용 정리.

Visual Studio C++ 활용 Visual Studio Visual C++ / C# 1.설치, 설정  주제  비고.  Visual Studio 2010 설치.  Visual Studio 2013 (Community)무료 설치.  Visaul Studio 2015 (Community)무료 설치...

igotit.tistory.com

 

 


첫 등록 : 2016.02.20

최종 수정 : 2022.03.07

단축 주소 : https://igotit.tistory.com/672


 

 

 

댓글0


   
현물 |선물 인버스 |선물 USDT     현물 | 선물 USDT |봇제작툴/카피트레이딩     현물 |선물 인버스 |선물 USDT     선물 인버스 |선물 USDT