Cpp time in seconds

How to Measure Elapsed Time in C++?

Measuring elapsed time is a common requirement for most software development packages. It is used to determine the efficiency of the program and gives an idea of which parts of the program takes which much time. This helps in optimizing the code, such that improves its execution time. In this article, you will learn how to measure elapsed time in C++.

* high_resolution_clock::now function of the chrono header file would be used in the process. This header file may not be present in older versions of GCC.

Measuring Elapsed Time

For measuring elapsed time, two timestamps would be collected. One at the beginning of the code and the other at the end. Then we would subtract the two timestamps, and the time difference between the two would provide us with the elapsed time.

C++

Explanation: The relevant header files were imported. At the beginning of the main code, a timestamp is taken by calling the high_resolution_clock::now function and the data is stored in variable beg. After which the actual code whose elapsed time is to be measured should come. For demonstration, a loop is run from 0 to 50000 which does nothing in its body. This is done to produce an event which takes some time. After which another call to the high_resolution_clock::now function is made and the return data is stored in the variable end.

After which the difference between the end and the beg variable is obtained, and the result is cast into milliseconds precision in the statement duration_cast(end – beg). This gives us the time taken between the first time the clock function is called, and the last time is was called. In the end, the elapsed time is displayed using the count function.

Note: The reason why milliseconds are chosen as the precision is that most computers are capable of executing such trivial tasks (like loops) in under a second. Therefore, if the precision was chosen as seconds, we would end up with 0 as the elapsed time. Therefore to demonstrate the effect milliseconds were chosen. This could be changed to another time precision by replacing microseconds between the angular brackets with the time frame of your choice.

Источник

std::chrono:: duration

Class template std::chrono::duration represents a time interval.

It consists of a count of ticks of type Rep and a tick period, where the tick period is a compile-time rational fraction representing the time in seconds from one tick to the next.

The only data stored in a duration is a tick count of type Rep . If Rep is floating point, then the duration can represent fractions of ticks. Period is included as part of the duration’s type, and is only used when converting between different durations.

Contents

[edit] Member types

Member type Definition
rep Rep , an arithmetic type representing the number of ticks
period Period (until C++17) typename Period::type (since C++17) , a std::ratio representing the tick period (i.e. the number of second’s fractions per tick)

[edit] Member functions

[edit] Non-member functions

[edit] Helper types

Type Definition
std::chrono::nanoseconds duration < /*signed integer type of at least 64 bits*/ , std:: nano >
std::chrono::microseconds duration < /*signed integer type of at least 55 bits*/ , std:: micro >
std::chrono::milliseconds duration < /*signed integer type of at least 45 bits*/ , std:: milli >
std::chrono::seconds duration < /*signed integer type of at least 35 bits*/ >
std::chrono::minutes duration < /*signed integer type of at least 29 bits*/ , std:: ratio < 60 >>
std::chrono::hours duration < /*signed integer type of at least 23 bits*/ , std:: ratio < 3600 >>
std::chrono::days (since C++20) duration < /*signed integer type of at least 25 bits*/ , std:: ratio < 86400 >>
std::chrono::weeks (since C++20) duration < /*signed integer type of at least 22 bits*/ , std:: ratio < 604800 >>
std::chrono::months (since C++20) duration < /*signed integer type of at least 20 bits*/ , std:: ratio < 2629746 >>
std::chrono::years (since C++20) duration < /*signed integer type of at least 17 bits*/ , std:: ratio < 31556952 >>
Читайте также:  Java method print string

Note: each of the predefined duration types up to hours covers a range of at least ±292 years.

Each of the predefined duration types days , weeks , months and years covers a range of at least ±40000 years. years is equal to 365.2425 days (the average length of a Gregorian year). months is equal to 30.436875 days (exactly 1/12 of years ).

[edit] Helper classes

[edit] Literals

Note: the literal suffixes d and y do not refer to days and years but to day and year, respectively.

[edit] Notes

The actual time interval (in seconds) that is held by a duration object d is roughly equal to d. count ( ) * D :: period :: num / D :: period :: den , where D is of type chrono::duration<> and d is an object of such type.

[edit] Example

This example shows how to define several custom duration types and convert between types:

#include #include using namespace std::chrono_literals; templatetypename T1, typename T2> using mul = std::ratio_multiplyT1, T2>; int main() { using shakes = std::chrono::durationint, mulstd::deca, std::nano>>; using jiffies = std::chrono::durationint, std::centi>; using microfortnights = std::chrono::durationfloat, mulmulstd::ratio2>, std::chrono::weeks::period>, std::micro>>; using nanocenturies = std::chrono::durationfloat, mulmulstd::hecto, std::chrono::years::period>, std::nano>>; using fps_24 = std::chrono::durationdouble, std::ratio1,24>>; std::cout  <"1 second is:\n"; // integer scale conversion with no precision loss: no cast std::cout  ::chrono::microseconds(1s).count()  <" microseconds\n"  (1s).count()  <" shakes\n"  (1s).count()  <" jiffies\n"; // integer scale conversion with precision loss: requires a cast std::cout  <std::chrono::duration_caststd::chrono::minutes>(1s).count()  <" minutes\n"; // floating-point scale conversion: no cast std::cout  (1s).count()  <" microfortnights\n"  (1s).count()  <" nanocenturies\n"  (1s).count()  <" frames at 24fps\n"; }
1 second is: 1000000 microseconds 100000000 shakes 100 jiffies 0 minutes 0.82672 microfortnights 0.316887 nanocenturies 24 frames at 24fps

Источник

time , _time32 , _time64

destTime
Указатель на место хранения для времени.

Возвращаемое значение

Возвращает время в секундах, прошедших с полуночи 1 января 1970 года, или -1, если возникла ошибка.

Комментарии

Функция time возвращает число секунд, истекших после полуночи (00:00:00) 1 января 1970 г. (в формате UTC) по системным часам. Возвращаемое значение сохраняется в расположении, предоставленном destTime . Этот параметр может иметь значение NULL , в этом случае возвращаемое значение не сохраняется.

time является оболочкой для _time64 , а time_t по умолчанию равнозначно __time64_t . Если необходимо, чтобы компилятор принудительно интерпретировал time_t как старое 32-разрядное значение time_t , можно определить _USE_32BIT_TIME_T . Не рекомендуется _USE_32BIT_TIME_T , так как приложение может завершиться сбоем после 18 января 2038 г.; использование этого макроса запрещено на 64-разрядных платформах.

Требования

Подпрограмма Обязательный заголовок C Обязательный заголовок C++
time , _time32 , _time64 или

Дополнительные сведения о совместимости см. в разделе Compatibility.

Пример

// crt_times.c // compile with: /W3 // This program demonstrates these time and date functions: // time _ftime ctime_s asctime_s // _localtime64_s _gmtime64_s mktime _tzset // _strtime_s _strdate_s strftime // // Also the global variable: // _tzname // // Turn off deprecated unsafe CRT function warnings #define _CRT_SECURE_NO_WARNINGS 1 #include #include #include #include #include #include int main() < char tmpbuf[128], timebuf[26], ampm[] = "AM"; time_t ltime; struct _timeb tstruct; struct tm today, gmt, xmas = < 0, 0, 12, 25, 11, 93 >; errno_t err; // Set time zone from TZ environment variable. If TZ is not set, // the operating system is queried to obtain the default value // for the variable. // _tzset(); // Display operating system-style date and time. _strtime_s( tmpbuf, 128 ); printf( "OS time:\t\t\t\t%s\n", tmpbuf ); _strdate_s( tmpbuf, 128 ); printf( "OS date:\t\t\t\t%s\n", tmpbuf ); // Get UNIX-style time and display as number and string. time( <ime ); printf( "Time in seconds since UTC 1/1/70:\t%lld\n", (long long)ltime ); err = ctime_s(timebuf, 26, <ime); if (err) < printf("ctime_s failed due to an invalid argument."); exit(1); >printf( "UNIX time and date:\t\t\t%s", timebuf ); // Display UTC. err = _gmtime64_s( &gmt, <ime ); if (err) < printf("_gmtime64_s failed due to an invalid argument."); >err = asctime_s(timebuf, 26, &gmt); if (err) < printf("asctime_s failed due to an invalid argument."); exit(1); >printf( "Coordinated universal time:\t\t%s", timebuf ); // Convert to time structure and adjust for PM if necessary. err = _localtime64_s( &today, <ime ); if (err) < printf("_localtime64_s failed due to an invalid argument."); exit(1); >if ( today.tm_hour >= 12 ) < strcpy_s( ampm, sizeof(ampm), "PM" ); today.tm_hour -= 12; >if ( today.tm_hour == 0 ) // Adjust if midnight hour. today.tm_hour = 12; // Convert today into an ASCII string err = asctime_s(timebuf, 26, &today); if (err) < printf("asctime_s failed due to an invalid argument."); exit(1); >// Note how pointer addition is used to skip the first 11 // characters and printf is used to trim off terminating // characters. // printf( "12-hour time:\t\t\t\t%.8s %s\n", timebuf + 11, ampm ); // Print additional time information. _ftime( &tstruct ); // C4996 // Note: _ftime is deprecated; consider using _ftime_s instead printf( "Plus milliseconds:\t\t\t%u\n", tstruct.millitm ); printf( "Zone difference in hours from UTC:\t%u\n", tstruct.timezone/60 ); printf( "Time zone name:\t\t\t\t%s\n", _tzname[0] ); //C4996 // Note: _tzname is deprecated; consider using _get_tzname printf( "Daylight savings:\t\t\t%s\n", tstruct.dstflag ? "YES" : "NO" ); // Make time for noon on Christmas, 1993. if( mktime( &xmas ) != (time_t)-1 ) < err = asctime_s(timebuf, 26, &xmas); if (err) < printf("asctime_s failed due to an invalid argument."); exit(1); >printf( "Christmas\t\t\t\t%s\n", timebuf ); > // Use time structure to build a customized time string. err = _localtime64_s( &today, <ime ); if (err) < printf(" _localtime64_s failed due to invalid arguments."); exit(1); >// Use strftime to build a customized time string. strftime( tmpbuf, 128, "Today is %A, day %d of %B in the year %Y.\n", &today ); printf( tmpbuf ); > 
OS time: 13:51:23 OS date: 04/25/03 Time in seconds since UTC 1/1/70: 1051303883 UNIX time and date: Fri Apr 25 13:51:23 2003 Coordinated universal time: Fri Apr 25 20:51:23 2003 12-hour time: 01:51:23 PM Plus milliseconds: 552 Zone difference in hours from UTC: 8 Time zone name: Pacific Standard Time Daylight savings: YES Christmas Sat Dec 25 12:00:00 1993 Today is Friday, day 25 of April in the year 2003. 

Источник

Measure time in C++

Learn Algorithms and become a National Programmer

You might be wondering how we measure time in C++ and most important is what kind of time we measure in C++? Now, the answer to this question is pretty easy we measure the execution time or CPU time.

Execution time: Execution time or CPU time is the time our machine/pc/CPU takes to complete a task(for example a function). In simple words the total time during which our program is running.

There are multiple ways to measure time in c++ which are listed below:-

imagetime

time() function

time() — returns the current calender time since 1 January 1970 (also Known as Epoch) when argument is NULL or gives the total time elapsed since the start of the function untill it is executed(Total running time of the function).On failure the function returns -1.

  • HeaderFile — time.h
  • Syntax — time_t time(NULL)
  • Output — It gives the value in seconds.
  • Parameter — arguments to store time(or result) or NULL pointer.

Let’s see the example to understand it easily.

#include #include using namespace std; int main()

So it’s the time since 1 January 1970 till your current date and time in seconds.
lets see another example.

#include //Headerfile which include all other headerfiles in c++ using namespace std; //Function to print fibonacci number int fib(int n) < if(n==1 or n==0)< return n; >return fib(n-1) + fib(n-2); > int main()

Now it’s the time taken by my pc to execute the above function.It may vary according to your CPU performance.

clock() function

clock() — returns the time consumed by the program during processing or number of clock ticks elapsed since an epoch.

  • HeaderFile — time.h
  • Syntax — clock_t clock(void)
  • Output — It gives the output in millisecond but to get the output in second you need to divide the result with CLOCKS_PER_SEC.On error -1 is returned.
#include using namespace std; int fib(int n) < if(n==1 or n==0)< return n; >return fib(n-1) + fib(n-2); > int main()< clock_t start_time = clock(); fib(50); clock_t end_time1 = clock(); clock_t result = end_time1 - start_time; cout
192777 milliseconds 192 seconds 

chrono library

Since chrono was introduced in C++11 it has become the stardard way of dealing with time and date in a program because of precision over time considering time and date might be different in different computer so work with a neutral tool chrono library was found which eliminates all the drawbacks that might be found in other methods.
Now the utilities to measure time in chrono library are as follows:

  • HeaderFile — chrono.h
  • Syntax — chrono::function_name
  • Output — It gives the value in seconds,milliseconds,microseconds based on how we want the output we will discuss with an example.

Program to show chrono library functions

#include #include using namespace std; // main function to measure elapsed time of a C++ program // using chrono library int fib(int n) < if(n==1 or n==0)< return n; >return fib(n-1) + fib(n-2); > int main() < auto start = chrono::steady_clock::now(); fib(40); auto end = chrono::steady_clock::now(); cout(end-start).count()(end-start).count()(end-start).count()(end-start).count()
1653745600 nanoseconds 1653745 microseconds 1653 milliseconds 1 seconds 

The difference between time() , clock() and chrono can easily be seen.

Источник

Оцените статью