C++ Tutorial

C++ Chrono

chrono measures time. Durations and clocks live in <chrono>.

Time as a number with a unit

<chrono> gives you durations (how long) and clocks (when). A duration is an integer plus a unit: milliseconds, seconds, microseconds. You print the integer with count(). You do not print a wall-clock date in this chapter, so nothing depends on locale or timezone.

Include <chrono>. The names sit in std::chrono. Withusing namespace std; you write chrono::milliseconds. StudyGrid compiles this as C++17 with g++ 13.

milliseconds and count()

Construct a duration with a number of ticks. chrono::milliseconds wait(250) is 250 milliseconds.wait.count() returns that 250. The unit is in the type, not in the printed number, so label the output yourself if a person will read it.

Example

#include <chrono>
#include <iostream>
using namespace std;

int main() {
  chrono::milliseconds pulse(250);
  chrono::seconds gap(3);
  cout << pulse.count() << endl;
  cout << gap.count() << endl;
  return 0;
}

Output is 250 then 3. Those are ticks in each type’s unit, not clock-face times.

duration_cast changes the unit

You cannot assign 2500 milliseconds to a chrono::seconds variable without saying how to convert. Integer conversion truncates toward zero: 2500 ms becomes 2 seconds, not 3. The tool ischrono::duration_cast<Target>(value).

Example

#include <chrono>
#include <iostream>
using namespace std;

int main() {
  chrono::milliseconds raw(2500);
  chrono::seconds whole = chrono::duration_cast<chrono::seconds>(raw);
  cout << raw.count() << endl;
  cout << whole.count() << endl;
  return 0;
}

Output is 2500 then 2. The leftover 500 milliseconds are dropped. Cast the other way and 2 seconds become 2000 milliseconds with no loss.

Add durations of the same kind

Two milliseconds values add. The sum is still milliseconds. This is ordinary arithmetic on the tick counts, with the unit kept by the type.

Example

#include <chrono>
#include <iostream>
using namespace std;

int main() {
  chrono::milliseconds a(120);
  chrono::milliseconds b(80);
  chrono::milliseconds sum = a + b;
  cout << sum.count() << endl;
  return 0;
}

Output is 200. Subtract the same way. Do not mix units until you duration_cast.

steady_clock around a loop

chrono::steady_clock is a clock that does not jump backward. Call now() before the work and after. Subtract the two time points. The difference is a duration. Cast it to a unit you want to print, then call count(). A tiny loop may be 0 milliseconds, so this example prints microseconds.

Example

#include <chrono>
#include <iostream>
using namespace std;

int main() {
  auto started = chrono::steady_clock::now();
  long long total = 0;
  for (int i = 1; i <= 200000; i++) {
    total += i;
  }
  auto finished = chrono::steady_clock::now();
  auto us = chrono::duration_cast<chrono::microseconds>(finished - started);
  auto ms = chrono::duration_cast<chrono::milliseconds>(finished - started);
  cout << total << endl;
  cout << us.count() << endl;
  cout << ms.count() << endl;
  return 0;
}

The first line is the sum, which is fixed. The next two lines are elapsed microseconds and milliseconds. Those counts depend on the machine. Milliseconds of a short loop are often 0. That is expected: the cast truncates. This program does not sleep and does not start a thread.

Print durations, not dates

system_clock can represent calendar time. Formatting that as a date needs locale, timezones, and extra headers. Skip it here. If you need “how long did this take?”, prefer steady_clock and printcount() of a duration.

PieceRole
millisecondsA length of time in ms
count()The integer ticks
duration_castConvert to another unit
steady_clock::now()A moment for measuring

Keep measurements boring

Time a loop, a sort, or a function you already understand. Print the duration. Do not parse dates, and do not wait on another thread. Next: static, which is about shared data and values that survive from one call to the next, not about clocks.

Run the listings at /cpp/try. Change 2500 in the cast example and watchwhole.count() follow integer division of milliseconds by 1000.

Worked examples

The short listings above are there so you can see the grammar. The programs here use the same statements on quantities that already have units: a speed, a pH, a count of bases. They are classroom numbers. Air resistance is ignored. g is 9.81 m/s² unless a line says otherwise.

Open them in the C++ editor at /cpp/try. Change one measurement and check whether the result still has the right unit.

Physics

CPU time for a running sum

Numerical methods get compared by error and by time. steady_clock measures a tight loop. The sum itself is 20.0 if you add 0.0001 two hundred thousand times — in exact decimal. Binary floating point will be close.

On a fast machine the reported time may print as 0. That is a coarse clock, not a proof the loop was skipped.

Example

#include <iostream>
#include <chrono>
using namespace std;
using namespace chrono;

int main() {
  auto start = steady_clock::now();
  double sum = 0.0;
  for (int i = 0; i < 200000; i++) sum += 0.0001;
  auto end = steady_clock::now();
  cout << "sum = " << sum << endl;
  cout << "ms = " << duration_cast<milliseconds>(end - start).count() << endl;
  return 0;
}

Astronomy

Seconds in a day

A mean solar day is 86400 s by definition of how we count civil time. A sidereal day is about 86164 s. chrono::seconds is how you write that duration so it is not a bare 86400 in three places.

1 d = 86400 s (civil)

Example

#include <iostream>
#include <chrono>
using namespace std;
using namespace chrono;

int main() {
  seconds day(86400);
  cout << "1 day = " << day.count() << " s" << endl;
  return 0;
}

FAQ: C++ Chrono

Common questions about this page.

What is the StudyGrid C++ tutorial?

The StudyGrid C++ tutorial is a full beginner-to-advanced track: syntax, types, input, loops, functions, classes, the STL, templates, maps, and lambdas. Each chapter has copy-and-run examples.

Should I run c++ chrono examples locally for better learning?

Yes. Use the browser editor on StudyGrid for a quick check, then Download the example and run it on your computer. Local runs show real errors and the real toolchain, which is one of the fastest ways to learn c++ chrono in this C++ C++ lesson (C++ Chrono).

Is the C++ editor the same as Try Python or Try HTML?

No. Try C++ compiles with g++ at /cpp/try and shows stdout plus compiler messages. Try Python stays at /try. Try HTML stays at /html/try. C++ lessons never open those editors.

Do I need to install a compiler to learn C++?

No. Open a chapter, click Try it in C++, and compile in the browser. You can also download a .cpp file and compile locally with g++.

Where should I start the C++ tutorial?

Start at C++ Intro, then Get Started and Syntax. After the first program, continue to output, variables, and if-else. After classes, open C++ Examples, then templates, map, and lambdas. Use Next at the bottom of each chapter.

Is the C++ tutorial free?

Yes. The C++ workshop on StudyGrid (studygrid.in) is free: dashboard, chapters, and the compile-and-run editor.