When using C + + coding, many C + + developers will be troubled when they encounter function points that need to process time and date. Some will develop their own time processing library, and some will use struct tm and time() provided by C. This article will recommend a simple and easy-to-use C + + time library. It comes from the boost library. After use, it can perfectly solve the time problem we encounter in development.
1 timer Library
The timer library is very small and mainly consists of three parts: 1) timer component; 2)progress_timer component; 3)progress_display component.
1.1 timer component
The timer component can be used to count the running performance of the program. The usage method is as follows:
#include <boost/timer.hpp> using namespace boost; int main() { timer t; int i=0; while(i<1000000) { i++; } cout<<t.elapsed()<<endl; }
The above code is to use the timer component provided by the boost library to count the time taken by the program after 1 million cycles. In addition, the change component also provides a restart() function to re count the time. The definition form is:
// return elapsed time in seconds double elapsed() const { return double(std::clock() - _start_time) / CLOCKS_PER_SEC; }
It should be noted that although the timer component is simple and easy to use, it is not suitable for statistical tasks requiring high time accuracy. Its accuracy depends on the platform on which the code runs. Naturally, it is not suitable for time statistics with high time span. Generally speaking, it is only used for time statistics in days at most.
1.2 progress_timer component
progress_timer component inherits from timer and is more convenient to use. Only one instance needs to be defined, and the statistical time will be automatically output when the instance object is destructed. The precision is reserved to two digits after the decimal point by default, and the unit is second.
Header files need to be included when using, as follows:
#include <boost/progress.hpp> using namespace boost;
When used in code, you can count the time of multiple code segments, but you need to design different life cycles for each code segment. The following code is shown:
int main() { { progress_timer t; DoSomthing(); } { progress_timer t; DoSomthing(); } }
As mentioned above, progress_ The timer component has completed all the work, and it is easier to use than the timer component. Of course, you can also make progress by yourself_ The time precision output by timer component is extended by modifying the source code or writing a new class. To modify the source code implementation, refer to the following code:
//The default time is accurate to two decimal places std::streamsize old_prec = m_os.precision( 2 );
If you add a new implementation class, you can use the template method to implement it in the original progress_ Most of the code in the timer component can be reused. Only the following modifications are required:
template <int N=2> class new_progress_timer:public boost::timer{ } //The method of use is: new_progress_timer<10> t;
1.3 progress_display component
The function of this component is to display the program loading or processing progress, which is similar to the progress bar in windows program. Provide feedback to users when the program is loaded slowly to show the real-time processing progress. The main application methods are as follows:
#include <boost/progress.hpp> using namespace std; int main() { std::vector<string> v(100); progress_display pd(v.size()); for (auto &x:v) { cout<<x; ++pd; for(int i = 0 ;i <1000000;i++) { } } return 0; }
After the program runs, the running result is shown in the following figure:

Using progress_ When displaying the output, display also has permissions that it cannot get rid of. For example, component output and program output cannot be separated. If the process is mixed with program output, the display will be confused.
If you want to keep the output effect unchanged during progress output and program output, you can re assign the progress output after each program output.
2 date_time library
When encoding date and time operations, various calculations are sometimes required, such as adding and subtracting dates, calculating leap years, months, days, weeks and other functions. If these operations are to be implemented by ourselves, they are often time-consuming and laborious, but the date provided by boost_ The time library does solve most of our problems. It is a flexible and easy-to-use date and time library.
2.1 description of date category
date_timer library log supports any date calculation from 1400-01-01 to 9999-12-31. If you want to use date_ The timer library needs to contain the following header files:
#include<boost/date_time/gregorian/gregoria.hpp> using namaspace boost::gregorian;
The date class is date_ The core of timer is very small, but it is very efficient. It mainly includes the following core functions:
template<class T, class calendar, class duration_type_> class BOOST_SYMBOL_VISIBLE date : private boost::less_than_comparable<T , boost::equality_comparable<T > > { date(year_type y, month_type m, day_type d); date(const ymd_type& ymd); year_type year() const; month_type month() const; day_of_week_type day_of_week() const; ymd_type year_month_day() const; //wait }
2.2 creation date
There are many ways to create a date object. When using the constructor of the date class to create a date object, if the passed in parameter is empty, an invalid date object will be generated. Similarly, if a date object is constructed in the order of the constructor, the corresponding date object will be created, such as:
date d1;//invalid date date d2(2021,12,29);//Create a date object date d3(d2);//By copying constructors date d4 = from_string("2021-12-29");//Create from string
2.3 date of visit
Many member functions are implemented in the date class to access dates, such as year_month_day() returns a calendar structure. You can access dates through calendar objects, such as:
date d2(2021,12,29);//Create a date object date::ymd_type ymd = d2.year_month_day(); assert(ymd.year == 2013); assert(ymd.month == 4); assert(ymd.day == 17); assert(d2.day_of_week() == 3); //Day of the week Sunday is 0 cout<<d2.day_of_year()<<endl; //What day of the year is it assert(d2.end_of_month() == date(2013,4,30));
2.4 date output
date is very convenient to convert images into strings. The boost library provides three functions for conversion.
- to_simple_string(): converts the date to a string of type YYYY-MMM-DD
- to_iso_string(): converts the date to a string of type YYYYMMDD
- to_iso_extended_string(): converts the date to a string of type YYYY-MM-DD
The method of use is as follows:
date d2(2021,12,29);//Create a date object cout<<to_simple_string(d2)<<endl; cout<<to_iso_string(d2)<<endl; cout<<to_iso_extended_string(d2)<<endl;
2.5 data conversion with tm
Date supports mutual conversion with date classes in C format, such as:
date d2(2021,12,29);//Create a date object tm t = to_tm(d2); date d3 = date_from_tm(t);
2.6 date calculation
The date class supports object operations, but the addition of two objects is meaningless. You can subtract to obtain days. As shown in the code:
#include <boost/date_time/gregorian/gregorian.hpp> using namespace boost; int main() { date d1(2020,12,29), d2(2021,12,29); cout << d2 - d1 << endl; assert(d1+(d2-d1) == d2); d1 += days(10); assert(d1.day() == 11); d1 += months(2); assert(d1.month() == 3 && d1.day() == 11); d1 -= years(10); assert(d2.year() == d1.year() = 4); }
3 processing time
date_time library is a subtle level of time library system, which can reach the nanosecond level at most. When using, you need to include the following header files:
#include<boost/date_time/posix_time/posix_time.hpp> using namaspace boost::posix_time;
3.1 time point ptime is date_ The core component of time uses 64 bit or 92 bit certificates to store time data, and the interface is small and easy to use. The implementation is as follows:
ptime t(second_clock::local_time()); ptime t(second_clock::universal_time()); ptime t(microsec_clock::local_time()); ptime t(microsec_clock::universal_time());
As above, the code explains how to construct time using different time precision types. In the boost code, microsec_clock is a template class. It is defined as follows:
template<class time_type> class microsec_clock{ };
Many static methods are provided in the template class, such as the above code:
static time_type local_time(); static time_type universal_time();
In addition, there are other methods that can be found in the header file microsec_time_clock.hpp found.
3.2 operation time object
ptime is date + time_ The combination of duration and its operation library is decomposed into a set of these two operations, as shown in the following code:
ptime p(date(2021,12,30),hours(12)+minutes(30));//It means 12:30 on December 30, 2021 date d = p.date(); time_duration td = p.time_of_day(); ptime p2 = p + hours(3);
The above code defines a ptime object, and then obtains the date and time parts respectively through the provided methods. Ptime can perform addition and subtraction operations. In the code, three hours are added to the p object, so p2 represents the date and time: 2021-12-30 15:30.
3.3 with tm and time_ Conversion of T
Ptime is different from date. It has no time_from_tm method. If you want to convert tm to ptime, you can use date_from_tm() is a live date object, which is converted from tm to time manually_ Duration object to construct the ptime object.
You can convert from ptime object to tm object directly, as shown in the code:
ptime p(date(2021,12,30),hours(12)+minutes(30)) tm t = to_tm(p);
3.4 format of time
date_time provides specially formatted components, such as date_facet and time_ The facet component formats the time. The method of use is as follows:
date d(2021,12,31); date_facet *df = new date_facet("%Y year%m month%d day"); cout.imbue(locale(cout.getloc(),df)); cout<<d<<endl;
The result displayed after the above code is run is December 31, 2021. Format the time as follows:
date d(2021,12,31); time_facet *df = new time_facet("%Y year%m month%d day %H spot %M branch %S%F second"); cout.imbue(locale(cout.getloc(),df)); cout<<ptime(d,hours(12)+minutes(30)+millisec(100))<<endl;
As above, the code operation result is: 12:30:00.100000 seconds on December 31, 2021.
4 Summary
As above, the date and time of boost are briefly introduced. The above library is small and easy to use, which can provide us with great convenience in C + + programming. Similarly, the boost library is also evolving. Some libraries may be outdated and need to be learned.
There are many other classes in the boost library, time and date processing library, such as the operation of time zone, which are not described in this paper. If you are interested, you can explore by yourself.
- EOF -