<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ profiling - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ profiling - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Tue, 25 Aug 2026 13:29:09 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/profiling/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ Keeping Time in C++: How to use the std::chrono API ]]>
                </title>
                <description>
                    <![CDATA[ Keeping track of time is a very important aspect of computer programs. Some common use cases are: Measure/profile the performance of certain parts of code. Do work at certain periods of time, from within a program.  Detect whether threads are in a d... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/cpp-std-chrono-api/</link>
                <guid isPermaLink="false">66b99d5fc39234149cf0114b</guid>
                
                    <category>
                        <![CDATA[ C++ ]]>
                    </category>
                
                    <category>
                        <![CDATA[ profiling ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Jayant Chowdhary ]]>
                </dc:creator>
                <pubDate>Mon, 04 Dec 2023 23:38:45 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/12/ClangCover.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Keeping track of time is a very important aspect of computer programs. Some common use cases are:</p>
<ul>
<li>Measure/profile the performance of certain parts of code.</li>
<li>Do work at certain periods of time, from within a program. </li>
<li>Detect whether threads are in a deadlock / taking too long to complete an operation.</li>
<li>Synchronize tasks between different components of software</li>
</ul>
<p>and many more…</p>
<p>This article will guide you through how you can measure time in modern C++. </p>
<h3 id="heading-prerequisites">Prerequisites</h3>
<ul>
<li>A basic understanding of C++: For readers not familiar with C++, <a target="_blank" href="https://www.freecodecamp.org/news/learn-c-with-free-31-hour-course/">Learn C++ Programming for Beginners – Free 31-Hour Course</a> is a helpful resource.</li>
<li>A quick read through Linux time tracking infrastructure – <a target="_blank" href="https://man7.org/linux/man-pages/man2/gettimeofday.2.html">such as you can find here</a> – will help you get familiar with the ideas presented in the article.</li>
</ul>
<h2 id="heading-common-ways-to-track-time-in-c">Common Ways to Track Time in C++</h2>
<p>This article covers how you can keep track of time in C++. In C, on UNIX like systems, you can use the <a target="_blank" href="https://linux.die.net/man/3/clock_gettime">clock_gettime()</a> function to keep track of time. It returns time in a structured way through the <a target="_blank" href="https://www.gnu.org/software/libc/manual/html_node/Time-Types.html"><code>timespec</code></a> struct. </p>
<p>The <a target="_blank" href="https://linux.die.net/man/3/clock_gettime"><code>clock_gettime()</code></a> /<a target="_blank" href="https://linux.die.net/man/2/gettimeofday">gettimeofday</a> function gives us back a filled <a target="_blank" href="https://www.gnu.org/software/libc/manual/html_node/Time-Types.html"><code>timespec</code></a> struct which has two fields:</p>
<ol>
<li><code>tv_sec</code>, which gives us the time in seconds since the time source – CLOCK_REALTIME / CLOCK_MONOTONIC that was passed into clock_gettime. The 'type' of this field is <a target="_blank" href="https://en.cppreference.com/w/c/chrono/time_t"><code>time_t</code></a> which is usually an integral value.</li>
<li><code>tv_nsec</code>, which gives the time after <code>tv_sec</code>, in nanoseconds since the time source that was specified while calling <code>clock_gettime()</code>. The type of this field is a long int.</li>
</ol>
<p>So why is <a target="_blank" href="https://linux.die.net/man/3/clock_gettime"><code>clock_gettime()</code></a> not good enough? The answer is that the members of <code>struct timespec</code> can easily be passed to functions as they're really just <code>int</code>s / <code>float</code>s. They're not strongly typed. </p>
<p>It's also easy to forget about the units in which they represent time while passing information around to functions. This can happen when you're dealing with projects that have thousands of lines of code.</p>
<p>So what's the solution?</p>
<p>##The std::chrono API</p>
<p>C++11 introduced the std::chrono API, which can help you avoid some of these problems.</p>
<p>There are 3 important parts of the API.</p>
<p>###1. <code>std::chrono::duration</code></p>
<p>As its name suggests, <code>std::chrono::duration</code> is a type that represents a time interval. The official C++ reference mentions that <code>std::chrono::duration</code> is a templated type with the following signature:</p>
<pre><code class="lang-cpp"><span class="hljs-keyword">template</span>&lt;
    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Rep</span>,
    <span class="hljs-title">class</span> <span class="hljs-title">Period</span> = <span class="hljs-title">std</span>:</span>:ratio&lt;<span class="hljs-number">1</span>&gt;
&gt; <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">duration</span>;</span>
</code></pre>
<p>Here, the <code>Rep</code> template parameter represents the type that is used to count 'ticks' of time. A tick is just a unit of time which is a given fraction of a second. <code>Period</code>, the second parameter, defines what exactly that fraction is.</p>
<p>So, for example, if you write:</p>
<pre><code class="lang-cpp"><span class="hljs-keyword">using</span> my_ms_type = <span class="hljs-built_in">std</span>::chrono::duration&lt;<span class="hljs-keyword">int</span>, <span class="hljs-built_in">std</span>::ratio&lt;<span class="hljs-number">1</span>, <span class="hljs-number">1000</span>&gt;&gt;

my_ms_type duration_ms duration = <span class="hljs-number">3</span>; <span class="hljs-comment">// error: cannot convert from int</span>
my_ms_type duration_ms duration_ok{<span class="hljs-number">3</span>} <span class="hljs-comment">// OK, can construct from int</span>
</code></pre>
<p><code>my_ms_type</code> is a type that has been defined, which counts in units of milliseconds (1/1000th of a second). This count is expressed as an integer. As you might be able to guess, the <code>Rep</code> template parameter is <code>int</code> and Period is <code>std::ratio&lt;1,1000&gt;</code> (which really is a way of saying 1/1000).</p>
<p>Now that it's clear how durations are represented, let's see what we can and cannot do with these.</p>
<p>If there is a function that takes in a <code>my_ms_type</code> duration and you instead try to pass in any non-<code>std::chrono::duration</code> type, you'll get a compiler error.</p>
<p>It is possible to implicitly convert between different types of <code>std::chrono::duration</code> as long as information isn't lost with the type of <code>Rep</code>, since the standard library can compute the relationship between two <code>std::chrono::duration</code>types. It is not possible to implicitly convert if there is a loss of information. For example:</p>
<pre><code class="lang-cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span><span class="hljs-meta-string">&lt;chrono&gt;</span></span>

<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>::chrono;
<span class="hljs-keyword">using</span> my_type_ms = <span class="hljs-built_in">std</span>::chrono::duration&lt;<span class="hljs-keyword">int</span>, <span class="hljs-built_in">std</span>::ratio&lt;<span class="hljs-number">1</span>, <span class="hljs-number">1000</span>&gt;&gt;;
<span class="hljs-keyword">using</span> my_type_ms_f = <span class="hljs-built_in">std</span>::chrono::duration&lt;<span class="hljs-keyword">float</span>, <span class="hljs-built_in">std</span>::ratio&lt;<span class="hljs-number">1</span>, <span class="hljs-number">1000</span>&gt;&gt;;
<span class="hljs-keyword">using</span> my_type_hundredth_s = <span class="hljs-built_in">std</span>::chrono::duration&lt;<span class="hljs-keyword">int</span>, <span class="hljs-built_in">std</span>::ratio&lt;<span class="hljs-number">1</span>, <span class="hljs-number">100</span>&gt;&gt;;
<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">f</span><span class="hljs-params">(my_type_ms millis)</span> </span>{}
<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span>
</span>{
   <span class="hljs-keyword">int</span> duration = <span class="hljs-number">2</span>;
   my_type_ms_f duration_f{<span class="hljs-number">2.5</span>};
   my_type_hundredth_s duration_compatible{<span class="hljs-number">100</span>};

   f(duration); <span class="hljs-comment">// error: could not convert 'duration' from 'int' to 'my_type_ms'</span>

   f(duration_f) <span class="hljs-comment">//error: since float -&gt; int will lose information</span>

   f(duration_compatible) <span class="hljs-comment">// OK since no information is lost</span>
}
</code></pre>
<p>The standard library also has some predefined <code>std::chrono::duration</code> template specializations for common time durations such as <code>std::chrono::duration::seconds</code>, <code>milliseconds</code>, <code>microseconds</code>, and so on.</p>
<p>You can also get the 'count' value contained in a duration by using the <code>count</code> method in a duration.</p>
<pre><code class="lang-cpp"><span class="hljs-built_in">std</span>::chrono::seconds duration{<span class="hljs-number">3</span>};
<span class="hljs-comment">// Prints: 'Duration count: 3 seconds'</span>
<span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"Duration count: "</span> &lt;&lt; duration.count() &lt;&lt; <span class="hljs-string">" seconds"</span>;
</code></pre>
<p>Interestingly, converting from a unit with higher precision like <code>nanosecond</code> to something with a lower precision such as <code>millisecond</code> may also lead to a loss of information. For these specific cases, you need to use an <em>explicit cast</em> for conversion. This is called <code>duration_cast</code>. For example:</p>
<pre><code class="lang-cpp">nanoseconds durationInNs = <span class="hljs-number">3000000000</span>;
seconds ms = duration_cast&lt;seconds&gt;(durationInNs); <span class="hljs-comment">//OK 3s</span>
durationInNs = <span class="hljs-number">3500000000</span>;
ms = duration_cast&lt;nanoseconds&gt;(durationInNs); <span class="hljs-comment">// OK 3s - truncates down</span>
</code></pre>
<p>Now that we know why <code>std::chrono::duration</code> is useful, let's move on. The next section explores <code>std::chrono::time_point</code>.</p>
<p>###2. <code>std::chrono::time_point</code></p>
<p><code>std::chrono::time_point</code> is a way of expressing a particular point in time – surprise, surprise! </p>
<p>If you think about it, how can you logically define a point in time ? We need to have a reference starting point and a duration from the starting point. This is exactly what <code>std::chrono::time_point</code> does. </p>
<p>The class declaration looks like this:</p>
<pre><code class="lang-cpp"><span class="hljs-keyword">template</span>&lt;
    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Clock</span>,
    <span class="hljs-title">class</span> <span class="hljs-title">Duration</span> = <span class="hljs-title">typename</span> <span class="hljs-title">Clock</span>:</span>:duration
&gt; <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">time_point</span>;</span>
</code></pre>
<p>There are two template parameters here:</p>
<p>The first one is <code>Clock</code> which represents a reference clock relative to which the point in time is being measured. For now, some examples of clocks are:</p>
<ul>
<li><code>system_clock</code>: this represents a real-world wall clock. It's useful when you want to measure time in terms of real-world times. It's important to note that the system time can usually be changed on any system, so you shouldn't depend on this clock to calculate time periods between tasks / performance profiling.</li>
<li><code>steady_clock</code>: this represents a monotonically increasing clock. It's useful when you need stop-watch like clock accounting.</li>
</ul>
<p>The second template parameter is <code>Duration</code> which is what we discussed in the previous section. A <code>time_point</code> needs to be associated with a <code>duration</code> type since that's what is being used to measure ticks since the 'epoch' of the <code>Clock</code>. </p>
<p>Epoch is just a way of saying a reference point in time. While there's no mandate for which reference to use, Unix Time - that is, the time since 00:00:00 Coordinated Universal Time (UTC), Thursday, 1 January 1970 is a common one.</p>
<p>Time points based on the <em>same</em> clock can be subtracted and not added. For example:</p>
<pre><code class="lang-cpp"><span class="hljs-keyword">auto</span> tp1 = <span class="hljs-built_in">std</span>::chrono::system_clock::now();
...
<span class="hljs-keyword">auto</span> tp2 = <span class="hljs-built_in">std</span>::chrono::system_clock::now()
<span class="hljs-keyword">auto</span> tp3 = <span class="hljs-built_in">std</span>::chrono::steady_clock::now();

<span class="hljs-keyword">auto</span> diff = tp2 - tp1; <span class="hljs-comment">// OK</span>
<span class="hljs-keyword">auto</span> add = tp1 + tp2; <span class="hljs-comment">// Not Ok</span>
<span class="hljs-keyword">auto</span> add = tp3 - tp2; <span class="hljs-comment">// Not Ok - based on different clocks</span>
</code></pre>
<p>Let's now see what clocks are.</p>
<p>###3. Clock Types</p>
<p>A <code>Clock</code> is a type that ties together <code>std::chrono::duration</code> and <code>std::chrono::time_point</code>. It has a function <code>now()</code> that returns the current <code>time_point</code>. The formal requirements for a type to be a <code>Clock</code> can be found in the C++ spec <a target="_blank" href="https://en.cppreference.com/w/cpp/named_req/Clock">here</a>.</p>
<p>As mentioned before, <code>system_clock</code> and <code>steady_clock</code> are two popular clocks provided by the standard library. Each clock has its own associated <code>duration</code> as well.</p>
<p>Each <code>time_point</code> is associated with some clock, since it really has to be relative to some given reference.</p>
<p>Finally, let's see some examples of how you can tie together <code>duration</code>, <code>time_point</code>, and <code>Clock</code>. Let's say you want to measure the time that looping 100,000,000 times takes in nanoseconds, and you also want to print out the current wall time:</p>
<pre><code class="lang-cpp"><span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;chrono&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;iostream&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;ratio&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;thread&gt;</span></span>
<span class="hljs-meta">#<span class="hljs-meta-keyword">include</span> <span class="hljs-meta-string">&lt;ctime&gt;</span></span>

<span class="hljs-keyword">using</span> <span class="hljs-keyword">namespace</span> <span class="hljs-built_in">std</span>::chrono;
<span class="hljs-keyword">constexpr</span> <span class="hljs-keyword">size_t</span> kIterations = <span class="hljs-number">100000000</span>;
<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">testFunction</span> <span class="hljs-params">()</span> </span>{
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">size_t</span> i = <span class="hljs-number">0</span>; i &lt; kIterations; i++) {
    }
}

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span>
</span>{
    <span class="hljs-keyword">auto</span> tStartSteady = <span class="hljs-built_in">std</span>::chrono::steady_clock::now();
    <span class="hljs-built_in">std</span>::<span class="hljs-keyword">time_t</span> startWallTime = system_clock::<span class="hljs-keyword">to_time_t</span>(system_clock::now());
    <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"Time start = "</span> &lt;&lt; <span class="hljs-built_in">std</span>::ctime(&amp;startWallTime) &lt;&lt; <span class="hljs-string">" \n"</span>;
    testFunction();
    <span class="hljs-keyword">auto</span> tEndSteady = <span class="hljs-built_in">std</span>::chrono::steady_clock::now();
    nanoseconds diff = tEndSteady - tStartSteady;
    <span class="hljs-built_in">std</span>::<span class="hljs-keyword">time_t</span> endWallTime = system_clock::<span class="hljs-keyword">to_time_t</span>(system_clock::now());
    <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"Time end = "</span> &lt;&lt; <span class="hljs-built_in">std</span>::ctime(&amp;endWallTime) &lt;&lt; <span class="hljs-string">" \n"</span>;
    <span class="hljs-built_in">std</span>::<span class="hljs-built_in">cout</span> &lt;&lt; <span class="hljs-string">"Time taken = "</span> &lt;&lt; diff.count() &lt;&lt; <span class="hljs-string">" ns"</span>;
    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>; 
}
</code></pre>
<p>The output of the program is the following:</p>
<pre><code>Output:
<span class="hljs-comment">// This can of course vary from system to system</span>
Time start = Tue Nov  <span class="hljs-number">7</span> <span class="hljs-number">07</span>:<span class="hljs-number">11</span>:<span class="hljs-number">13</span> <span class="hljs-number">2023</span>

Time end = Tue Nov  <span class="hljs-number">7</span> <span class="hljs-number">07</span>:<span class="hljs-number">11</span>:<span class="hljs-number">13</span> <span class="hljs-number">2023</span>

Time taken = <span class="hljs-number">50998885</span> ns
</code></pre><h2 id="heading-summary">Summary</h2>
<p>This article explored various facets of the <code>std::chrono</code> API in C++. The <code>std::chrono</code> API allows C++ programmers to safely keep track of time thanks to its strongly typed system. It also helps maintain support for convenient conversions between different 'types' of time points.</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
