Selected Reading

C++ chrono::operator*() Function



The std::chrono::operator*() function in C++, is used to multiply a duration object by a scalar value or vice versa. It enables the arithmetic operations involving durations, such as scaling a time interval by a factor.

It is used for the duration types and returns a new duration object with the scaled value while maintaining the same time unit (seconds, milliseconds).

Syntax

Following is the syntax for std::chrono::operator*() function.

operator* (const duration<Rep1,Period>& lhs, const Rep2& r)

Parameters

  • lhs − It indicates the duration objects.
  • r − It indicates a value of an arithmetic type, or an object of a class emulating an arithmetic type.

Return value

This function returns the result of the operation.

Example 1

Let's look at the following example, where we are scaling a duration by an integer.

#include <iostream>
#include <chrono>
int main() {
   std::chrono::seconds x(6);
   auto a = x * 2;
   std::cout << "Result : " << a.count() << " seconds\n";
   return 0;
}

Output

Output of the above code is as follows −

Result : 12 seconds

Example 2

Consider the following example, we are going to use the operator*() with the negative scalar.

#include <iostream>
#include <chrono>
int main() {
   std::chrono::minutes y(4);
   auto a = y * -2;
   std::cout << "Result : " << a.count() << " minutes\n";
   return 0;
}

Output

Following is the output of the above code −

Result : -8 minutes
cpp_chrono.htm
Advertisements