C++ duration | 'Time Interval' Guide

C++ duration | 'Time Interval' Guide

이 글의 핵심

C++ duration C++, duration, "time, 1.

Introduction

std::chrono::duration is a type representing time intervals. It’s type-safe, has clear unit conversion, and supports time operations.


Reality in Production

When learning development, everything is clean and theoretical. But production is different. You wrestle with legacy code, chase tight deadlines, and face unexpected bugs. The content covered in this guide was initially learned as theory, but I realized “ah, that’s why it’s designed this way” while applying it to actual projects.

What stands out in my memory is the trial and error from my first project. I did it as I learned from books but spent days not knowing why it didn’t work. Eventually, I found the problem through a senior developer’s code review and learned a lot in the process. This guide covers not only theory but also pitfalls you may encounter in practice and their solutions.

1. duration Basics

Basic Usage

Here is detailed implementation code using C++. Import the necessary modules. Understand the role of each part while examining the code.

#include <chrono>
#include <iostream>

int main() {
    using namespace std::chrono;
    
    // Create time interval: duration type
    // std::chrono::seconds: seconds unit duration
    seconds sec(10);  // 10 seconds
    // std::chrono::milliseconds: milliseconds unit duration
    milliseconds ms(10000);  // 10000 milliseconds = 10 seconds
    // std::chrono::minutes: minutes unit duration
    minutes min(1);  // 1 minute = 60 seconds
    // std::chrono::hours: hours unit duration
    hours hr(1);  // 1 hour = 60 minutes = 3600 seconds
    
    // Get value: extract numeric value with count() method
    std::cout << "Seconds: " << sec.count() << std::endl;  // 10
    std::cout << "Milliseconds: " << ms.count() << std::endl;  // 10000
    
    return 0;
}

Standard duration Types

Below is an implementation example using C++. Import the necessary modules. Understand the role of each part while examining the code.

#include <chrono>

// C++11 standard units
std::chrono::hours h(1);
std::chrono::minutes m(60);
std::chrono::seconds s(3600);
std::chrono::milliseconds ms(3600000);
std::chrono::microseconds us(3600000000);
std::chrono::nanoseconds ns(3600000000000);

// All represent 1 hour

2. Time Conversion

Implicit Conversion (Higher → Lower)

Here is detailed implementation code using C++. Import the necessary modules. Understand the role of each part while examining the code.

#include <chrono>
#include <iostream>

int main() {
    using namespace std::chrono;
    
    seconds s(10);  // 10 seconds
    
    // ✅ Higher → Lower (implicit conversion possible)
    // Large unit → Small unit: no information loss
    // seconds → milliseconds: 10 seconds = 10000 milliseconds
    milliseconds ms = s;  // 10000ms (auto conversion)
    // seconds → microseconds: 10 seconds = 10000000 microseconds
    microseconds us = s;  // 10000000us (auto conversion)
    
    std::cout << "Milliseconds: " << ms.count() << std::endl;  // 10000
    std::cout << "Microseconds: " << us.count() << std::endl;  // 10000000
    
    return 0;
}

Explicit Conversion (Lower → Higher)

Here is detailed implementation code using C++. Import the necessary modules. Understand the role of each part while examining the code.

#include <chrono>
#include <iostream>

int main() {
    using namespace std::chrono;
    
    milliseconds ms(1500);  // 1500 milliseconds = 1.5 seconds
    
    // ❌ Lower → Higher (implicit not allowed)
    // Small unit → Large unit: possible information loss (truncate decimals)
    // seconds s = ms;  // Compile error: explicit conversion needed
    
    // ✅ duration_cast (explicit conversion)
    // duration_cast<seconds>: convert milliseconds to seconds
    // 1500ms → 1s (500ms truncated)
    seconds s = duration_cast<seconds>(ms);  // 1s (truncated)
    
    std::cout << "Seconds: " << s.count() << std::endl;  // 1
    
    return 0;
}

C++17 Rounding Functions

Here is detailed implementation code using C++. Import the necessary modules. Understand the role of each part while examining the code.

#include <chrono>
#include <iostream>

int main() {
    using namespace std::chrono;
    
    milliseconds ms(1500);  // 1500 milliseconds = 1.5 seconds
    
    // duration_cast: truncate (discard decimals)
    // 1.5 seconds → 1 second (0.5 seconds discarded)
    auto s1 = duration_cast<seconds>(ms);
    std::cout << "Truncate: " << s1.count() << "s" << std::endl;  // 1s
    
    // round: round (C++17)
    // 1.5 seconds → 2 seconds (round up since >= 0.5)
    auto s2 = round<seconds>(ms);
    std::cout << "Round: " << s2.count() << "s" << std::endl;  // 2s
    
    // ceil: ceiling (C++17)
    // 1.5 seconds → 2 seconds (always round up)
    auto s3 = ceil<seconds>(ms);
    std::cout << "Ceil: " << s3.count() << "s" << std::endl;  // 2s
    
    // floor: floor (C++17)
    // 1.5 seconds → 1 second (always round down, same as duration_cast)
    auto s4 = floor<seconds>(ms);
    std::cout << "Floor: " << s4.count() << "s" << std::endl;  // 1s
    
    return 0;
}

3. Time Operations

Arithmetic Operations

Here is detailed implementation code using C++. Import the necessary modules. Understand the role of each part while examining the code.

#include <chrono>
#include <iostream>

int main() {
    using namespace std::chrono;
    
    seconds s1(10);
    seconds s2(5);
    
    // Addition
    auto sum = s1 + s2;
    std::cout << "Sum: " << sum.count() << "s" << std::endl;  // 15s
    
    // Subtraction
    auto diff = s1 - s2;
    std::cout << "Diff: " << diff.count() << "s" << std::endl;  // 5s
    
    // Multiplication
    auto mul = s1 * 2;
    std::cout << "Multiply: " << mul.count() << "s" << std::endl;  // 20s
    
    // Division
    auto div = s1 / 2;
    std::cout << "Divide: " << div.count() << "s" << std::endl;  // 5s
    
    // Modulo
    auto mod = s1 % s2;
    std::cout << "Modulo: " << mod.count() << "s" << std::endl;  // 0s
    
    return 0;
}

Summary

Key Points

  1. duration: Represents time intervals
  2. Standard types: hours, minutes, seconds, milliseconds, etc.
  3. Conversion: Implicit (higher→lower), explicit (lower→higher)
  4. Operations: Arithmetic and comparison supported
  5. Literals: C++14 supports 10s, 500ms syntax

When to Use

Use duration when:

  • Need type-safe time intervals
  • Want clear unit conversion
  • Measuring elapsed time
  • Implementing timeouts

Don’t use when:

  • Simple integer milliseconds sufficient
  • Need calendar dates (use time_point)

Best Practices

  • ✅ Use appropriate unit for context
  • ✅ Use literals for readability (C++14+)
  • ✅ Use duration_cast for explicit conversion
  • ❌ Don’t mix units without conversion
  • ❌ Don’t use raw integers for time

Master duration for type-safe time handling! 🚀