Timing in C++

The Cherno · Intermediate ·🛡️ AI Safety & Ethics ·8y ago

Key Takeaways

The video demonstrates the use of the Chronos library in C++ for high-resolution timing and performance evaluation, including the use of the STD chrono high_resolution_clock, Query performance counter, and Thread sleep function. The video also covers platform-independent timing, object lifetime paradigm, and instrumentation for profiling.

Full Transcript

hey what's up guys my name is a China welcome back to my c++ series so today we're gonna be talking all about timing so how do we time how long it takes for us to complete a certain operation or execute certain code that is what today's we are going to be about now timing is useful for so many things whether or not you want something to happen at a certain time or if you're just kind of evaluating your performance or benchmarking and seeing how fast your code runs you need to know how much time passes while you up while your application is actually running there are several ways to achieve this since C++ 11 we have something called Chronos essentially say it's essentially part of the library that is becomes with C++ and it's not something that we actually have to go to the operating system library to actually do before if you wanted a high resolution time on meaning you wanted a very very precise timer you need to actually use the operating systems library so in Windows for example we have something called query performance counter we can still use that stuff and in fact if you want a little bit more control of how you actually access that timing capability of your CPU then you probably do want to use the platform specific libraries however today we're just going to be taking a look at the kind of platform-independent c++ standard library way of figuring out how long or how much time passes between our lines of code as they get executed and that is part of the chrono library now I've linked a link in the description below to the actual cpp reference for this chrono kind of API I'm going to show you a very simple way of how we can set it up and start using it here so that we can figure out how long it takes us to run certain code and I'll probably also show you one way in which it can be useful now this whole video is going to be important for the future of this series because as we start integrating more kind of complex features and I start talking more and more about how to do things properly and how to write good performing code we're going to be using timing to see that difference so if I show you a kind of slow way of doing things and then I say well actually it would be better if we did it this way you'll be able to actually see the difference in terms of how long it takes to actually run that code so this is very important from this will probably branch into benchmarking and I'll talk more about benchmarking in another video and we can set up some kind of API so that we can time how long it takes to complete functions and arbitrary scopes code probably as well so yeah pay attention to this video let's jump right into it and learn how we can time a curve so the first thing I'm going to do here is include Krona this contains pretty much everything we need I'm also going to include thread because we'll do some stuff with that in a minute as well so from chrono it's very very simple to actually use that library and figure out what the current time is we can just type in STD chrono high resolution clock and then now this is what actually gives us the current time if you hover over this you can see it returns a time point of SUV current sit o'clock it's quite a long type which is why I'm just going to use order and kind of label this as the starting time we're then going to execute some kind of code here what I'm going to do for now because I don't actually have any other code to execute of the week and time I'm just going to write sed this thread sleep for and then we'll just write 1s for one second and to get that will actually have to use a namespace STD literals and chrono literals to get that s there okay cool so basically what we're doing now is we're telling this thread this current thread to sleep for one second so we're saying just kind of pauses pause execution for one second so obviously by writing this code when we have our start and our end timing we should see it be around one second probably won't be exactly one second because first of all thread sleeps are not guaranteed to be exactly how much you tell it to sleep for but also they'll be overhead from the actual timing so if we get back into this I'll right order end and this will be exactly the same as this start code here and finally we want to figure out the actual duration so I'll write SVD chrono duration well we can just get this in floats that'll be high enough resolution for us I'll call this duration and it will just be end minus start just like that we could have used order here as well but this type isn't quite as long so it's fine to write down and finally I'm just going to see out that into the console direction don't count and and this will be in seconds I'll just add s to the end of that so that's clear if I hit f5 you can see the number we get here is pretty much around one second so that's it what I just showed you is a platform-independent way of actually figuring out how long something takes or how much time passes or getting the current time and all that this kernel library is fantastic it's very high resolution timing and it works on pretty much all platforms so really I recommend that you use this for all of your timing needs unless you're specifically doing some kind of low-level things so you want to reduce overhead even more if you're running a huge game engine or some kind of cool library you might want to use the platform independent I'm sorry the platform specific library such as the win32 api with the query performance counter and stuff we might look into that in the future but really there's pretty much no need for 99% of cases just use STD kroehner now if we dive back into this I'm going to show you a bit of a smarter way of actually dealing with this because you can see that this is quite a lot of code that we have to run so support suppose that we have a function I'll call it function and it does something like maybe just prints out in our hello to the console a bunch of times so I'll just wrap this in a for loop and I'll say maybe it does that about a hundred times or something like that right so we have a for loop it runs a hundred times we want to figure out well how long is this see out operation really how long does it take C out to actually write stuff out to the console a hundred times I want to time this function so what I could do at this point is copy start and end and do all of that stuff that's a lot of work I don't really want to do that instead I'm actually going to set up a very very basic struct or class doesn't matter just make this a struct called timer and this will actually do everything for me and what I'm going to do here is I'm going to use the whole object lifetime kind of paradigm to actually get it to basically automatically time everything for me if you guys haven't checked out the video on object lifetime and C++ definitely do that it's very very useful and in fact this example I'm pretty sure I did actually give in that video as well and so jumping back into our code the constructor is going to actually start the timer so I'm going to grab this and put it in here unfortunately I actually use order so I'm gonna have to figure out what the type is which is sed Pro note time point s any corner City cloth so TV chrono time point s TV chrono steady clock so that's how kind of start just call this start and put it up here so we have our start and our end and I also grabbed this from here a direction and put this in that's the duration start I'm going to assign to this in the constructor and in the destructor when I copy this whole code here in the in the destructor what I'm actually going to do is write and equals the same thing and then finally curation and I mean you don't really have to store and as you can see because we're really just up at the duration but in case people want to access that maybe I want to kind of write that into my timer struct so generation equals and minus dot and that will give us the direction in seconds of course okay and that's really all I need let's just make it even easier and say that we actually print the duration so we'll say time I took and then I'll write in duration seconds now because this is such a quick operation we actually might want to print the milliseconds instead so I will say flirt M s equals duration of count times 1,000 which will give us the value in milliseconds and I'll change this to be m/s and this to be MS okay cool sounds pretty good to me that's pretty much all I need here and now we have a basic structure that will basically do the timing and even print it up for us automatically and it will of course do that upon destruction all we really need to do is just create the object at the beginning of our function and that's that's it so over here in my function the way I'm going to do this is just type in time a time up like that that's all I have to do and I'm done this entire scope this entire function will now be timed so if I go back and delete all of this crap that I that I don't care about I'm just going to call function like that and we'll hit f5 and say what happens okay cool so check this out we get pelo printing a hundred times to the console and at the very end we say that this took 122 milliseconds cool so we now know how long our part actually takes 122 milliseconds very very slow let's see if we might be able to optimize a little bit so a CDN line seems to be quite slower for some reason so if we just get rid of that and actually put a backslash n into our print here inside our function let's see how much faster this will be and you can see over here that we've caught out about a third of our execution time obviously you should run this a few more times and in release mode if you actually care about benchmarking and all of that but for now we can still see the difference anyway that is a basic overview of timing in C++ and how you can time your functions and see how long it takes to execute certain code obviously this was a very very rough example I was just showing you how to actually use that timing API not how to actually perform benchmarks we're going to have a video all about that in the future you can of course also use visual studios profiling tools or whatever idea you're using whatever tool say you're using a lot of tools do have profiling tools built in so you can actually automate a lot of this this is more or less something called instrumentation where you actually modify your source code to contain kind of profiling tools such as this timing that can be very very useful because not all platforms you work with are going to have good enough profile of the dart and overhead and this is a really simple way to do it there are so many things that you can actually do from this you can basically collect the data into like one big file and output it and read it in another tool so that you can see graphs or even like kind of a diagram of how long each function takes and what function that function calls and there's so many things that will extend from this that we'll explore in the future so definitely get excited about that very important that you start doing this if you do care about performance since I imagine a lot of people watching this series are game developers or people who want to write game engines you need to be doing stuff like this all the time to actually see how fast your probe performs and since you are using C++ as a language you're using C++ probably because you care about performance and you want to write fast code so definitely get used to this kind of stuff anyway I hope you guys enjoyed this video if you did you can hit the like button you can also help support this series by going over to patreon look on 4/2 churner huge thank you as always to all of my patrons this series would not be here without you I can kind of cent guarantee that so they he's so much and I will see you guys in the next video goodbye [Music]

Original Description

Patreon ► https://patreon.com/thecherno Instagram ► https://instagram.com/thecherno Twitter ► https://twitter.com/thecherno Discord ► https://thecherno.com/discord chrono reference ► http://en.cppreference.com/w/cpp/chrono Series Playlist ► https://thecherno.com/cpp Thank you to the following Patreon supporters: - Dominic Pace - Kevin Gregory Agwaze - Sébastien Bervoets - Tobias Humig - Peter Siegmund - Kerem Demirer Gear I use: ----------------- BEST laptop for programming! ► http://geni.us/pakTES My FAVOURITE keyboard for programming! ► http://geni.us/zNhB FAVOURITE monitors for programming! ► http://geni.us/Ig6KBq MAIN Camera ► http://geni.us/t6xyDRO MAIN Lens ► http://geni.us/xGoDWT Second Camera ► http://geni.us/CYUQ Microphone ► http://geni.us/wqO6g7K
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from The Cherno · The Cherno · 0 of 60

← Previous Next →
1 3D Game Programming - Episode 1 - Window
3D Game Programming - Episode 1 - Window
The Cherno
2 3D Game Programming - Episode 2 - Game Loop
3D Game Programming - Episode 2 - Game Loop
The Cherno
3 3D Game Programming - Episode 3 - Arrays
3D Game Programming - Episode 3 - Arrays
The Cherno
4 3D Game Programming - Episode 4 - Drawing Pixels!
3D Game Programming - Episode 4 - Drawing Pixels!
The Cherno
5 3D Game Programming - Episode 4.5 - How Rendering Works
3D Game Programming - Episode 4.5 - How Rendering Works
The Cherno
6 3D Game Programming - Episode 5 - Playing with Pixels!
3D Game Programming - Episode 5 - Playing with Pixels!
The Cherno
7 3D Game Programming - Episode 6 - Performance Boosting
3D Game Programming - Episode 6 - Performance Boosting
The Cherno
8 3D Game Programming - Episode 7 - FPS Counter
3D Game Programming - Episode 7 - FPS Counter
The Cherno
9 3D Game Programming - Episode 8 - Alpha Support and More
3D Game Programming - Episode 8 - Alpha Support and More
The Cherno
10 3D Game Programming - Episode 9 - Beginning 3D
3D Game Programming - Episode 9 - Beginning 3D
The Cherno
11 3D Game Programming - Episode 10 - Floors and Animation
3D Game Programming - Episode 10 - Floors and Animation
The Cherno
12 3D Game Programming - Episode 11 - Rotation
3D Game Programming - Episode 11 - Rotation
The Cherno
13 3D Game Programming - Episode 12 - User Input
3D Game Programming - Episode 12 - User Input
The Cherno
14 3D Game Programming - Episode 13 - Render Distance Limiter!
3D Game Programming - Episode 13 - Render Distance Limiter!
The Cherno
15 3D Game Programming - Episode 14 - Basic Mouse Movement
3D Game Programming - Episode 14 - Basic Mouse Movement
The Cherno
16 3D Game Programming - Episode 15 - Textures + More!
3D Game Programming - Episode 15 - Textures + More!
The Cherno
17 3D Game Programming - Episode 16 - Walking, Crouching, Sprinting + More
3D Game Programming - Episode 16 - Walking, Crouching, Sprinting + More
The Cherno
18 3D Game Programming - Episode 16.5 - Exporting Runnable Jars
3D Game Programming - Episode 16.5 - Exporting Runnable Jars
The Cherno
19 3D Game Programming - Episode 17 - Small Adjustments + Birthday!
3D Game Programming - Episode 17 - Small Adjustments + Birthday!
The Cherno
20 3D Game Programming - Episode 17.5 - Creating an Applet
3D Game Programming - Episode 17.5 - Creating an Applet
The Cherno
21 3D Game Programming - Episode 18 - The Beginning of Walls
3D Game Programming - Episode 18 - The Beginning of Walls
The Cherno
22 3D Game Programming - Episode 18.1 - A Few More Things
3D Game Programming - Episode 18.1 - A Few More Things
The Cherno
23 Episode 18.5 - Creating an EXE File in Java
Episode 18.5 - Creating an EXE File in Java
The Cherno
24 3D Game Programming - Episode 19 - Rendering Walls
3D Game Programming - Episode 19 - Rendering Walls
The Cherno
25 3D Game Programming - Episode 20 - Continuing Walls, Fixing Bugs, and Managing Crashes
3D Game Programming - Episode 20 - Continuing Walls, Fixing Bugs, and Managing Crashes
The Cherno
26 3D Game Programming - Episode 21 - Texturing Walls, Fixing Clipping, and Fixing the Mouse
3D Game Programming - Episode 21 - Texturing Walls, Fixing Clipping, and Fixing the Mouse
The Cherno
27 3D Game Programming - Episode 22 - Random Level Generator + Properly Fixing Clipping
3D Game Programming - Episode 22 - Random Level Generator + Properly Fixing Clipping
The Cherno
28 3D Game Programming - Episode 23 - Graphical User Interface (GUI) Launcher
3D Game Programming - Episode 23 - Graphical User Interface (GUI) Launcher
The Cherno
29 3D Game Programming - Episode 24 - Making Our Launcher Work
3D Game Programming - Episode 24 - Making Our Launcher Work
The Cherno
30 3D Game Programming - Episode 25 - Writing and Reading Files
3D Game Programming - Episode 25 - Writing and Reading Files
The Cherno
31 3D Game Programming - Episode 26 - Custom Resolutions
3D Game Programming - Episode 26 - Custom Resolutions
The Cherno
32 3D Game Programming - Episode 27 - Decorating the Launcher
3D Game Programming - Episode 27 - Decorating the Launcher
The Cherno
33 3D Game Programming - Episode 28 - Continuing our Custom Launcher!
3D Game Programming - Episode 28 - Continuing our Custom Launcher!
The Cherno
34 3D Game Programming - Episode 29 - Launching The Game
3D Game Programming - Episode 29 - Launching The Game
The Cherno
35 3D Game Programming - Episode 30 - Colour Processing In-Depth
3D Game Programming - Episode 30 - Colour Processing In-Depth
The Cherno
36 3D Game Programming - Episode 31 - Sprites!
3D Game Programming - Episode 31 - Sprites!
The Cherno
37 3D Game Programming - Episode 32 - Sprite Mapping
3D Game Programming - Episode 32 - Sprite Mapping
The Cherno
38 3D Game Programming - Episode 33 - High Resolution Rendering
3D Game Programming - Episode 33 - High Resolution Rendering
The Cherno
39 3D Game Programming - Episode 34 - Entities
3D Game Programming - Episode 34 - Entities
The Cherno
40 Genesis - My Game for Ludum Dare 24
Genesis - My Game for Ludum Dare 24
The Cherno
41 Vlog + Ludum Dare Results
Vlog + Ludum Dare Results
The Cherno
42 Game Programming - Episode 1 - Resolution
Game Programming - Episode 1 - Resolution
The Cherno
43 Game Programming - Episode 2 - Threads
Game Programming - Episode 2 - Threads
The Cherno
44 Game Programming - Episode 3 - Game Loop
Game Programming - Episode 3 - Game Loop
The Cherno
45 Game Programming - Episode 4 - Window
Game Programming - Episode 4 - Window
The Cherno
46 Episode 5 - Buffer Strategy
Episode 5 - Buffer Strategy
The Cherno
47 Game Programming - Episode 6 - Graphics Initialized
Game Programming - Episode 6 - Graphics Initialized
The Cherno
48 Game Programming - Episode 7 - Buffered Image and Rasters
Game Programming - Episode 7 - Buffered Image and Rasters
The Cherno
49 Game Programming - Episode 8 - The Screen Class
Game Programming - Episode 8 - The Screen Class
The Cherno
50 Game Programming - Episode 9 - Rendering Pixels
Game Programming - Episode 9 - Rendering Pixels
The Cherno
51 Game Programming - Episode 10 - Clearing the Screen
Game Programming - Episode 10 - Clearing the Screen
The Cherno
52 Game Programming - Episode 11 - "Out of Bounds, Baby!"
Game Programming - Episode 11 - "Out of Bounds, Baby!"
The Cherno
53 Game Programming - Episode 12 - Negative Bounds
Game Programming - Episode 12 - Negative Bounds
The Cherno
54 Game Programming - Episode 13 - Timer
Game Programming - Episode 13 - Timer
The Cherno
55 Game Programming - Episode 14 - FPS Counter
Game Programming - Episode 14 - FPS Counter
The Cherno
56 Episode 15 - Tiles
Episode 15 - Tiles
The Cherno
57 Game Programming - Episode 16 - The Map
Game Programming - Episode 16 - The Map
The Cherno
58 The Walls 2 - Minecraft PvP Survival Map
The Walls 2 - Minecraft PvP Survival Map
The Cherno
59 Game Programming - Episode 17 - Key Input
Game Programming - Episode 17 - Key Input
The Cherno
60 Game Programming - Episode 18 - Controlling The Map
Game Programming - Episode 18 - Controlling The Map
The Cherno

This video teaches the use of the Chronos library in C++ for high-resolution timing and performance evaluation, including platform-independent timing and instrumentation for profiling. It is essential for game developers and engine writers who prioritize performance optimization and want to learn how to use C++ for its performance benefits.

Key Takeaways
  1. Include the Chronos library in your C++ project
  2. Use the STD chrono high_resolution_clock to get the current time
  3. Create a timer struct to automatically time code execution
  4. Use the Query performance counter for high-resolution timing on Windows
  5. Use instrumentation to modify source code for profiling
  6. Visualize function call times and dependencies using a tool
  7. Import data into a single file for analysis
💡 The Chronos library provides a convenient and platform-independent way to achieve high-resolution timing in C++, making it an essential tool for game developers and engine writers who prioritize performance optimization.

Related Reads

📰
AI Safety Showdown
Explore the capabilities and limitations of various AI models, including GPT, Gemini, Qwen, Grok, Nano Banana, and Seedream, to understand AI safety concerns
Medium · AI
📰
The AI Jailbreak Problem Isn’t Gone Yet
The AI jailbreak problem persists, posing risks to LLM security and frontier models, and understanding its implications is crucial for AI safety
Medium · AI
📰
Building AI Security Blue Team Defenses on Existing Codebases with Kiro
Learn to build AI security blue team defenses on existing codebases with Kiro to protect against attacks on AI agents
Dev.to · Sandeep Chakravartty
📰
How AI Is Changing Cyber Hiring (What Matters vs Hype)
AI is transforming cyber hiring, but it's crucial to separate hype from reality and focus on skills that truly matter
Medium · Cybersecurity
Up next
Big Tech Is Turning Its Own Workers Into AI Training Data
AI Uncovered
Watch →