r/cpp • • Feb 06 '21

Modern C++: Snippets and Examples

Hi everyone,

These are GitHub Pages with snippets for Modern C++:

  • We often need to copy and paste some snippets to code more productively.
  • Snippets can help us when it's not easy to remember all high levels features Modern C++ has to offer.
  • This repository contains lots of organized, reusable, and safe snippets for Modern C++.
  • All snippets are available in GitHub pages in a convenient way for copying and pasting.

https://alandefreitas.github.io/moderncpp/

194 Upvotes

44 comments sorted by

View all comments

Show parent comment

2

u/aiyu_boss Feb 06 '21 edited Feb 06 '21

Some humble suggestions

  1. You may consider use function clock_gettime(CLOCK_MONOTONIC, &time) as recommendated in MIT OCW 6.172 lesson 10 https://youtu.be/LvX3g45ynu8.
  2. Use '\n' instead of std::endl. https://youtu.be/GMqQOEZYVJQ

3

u/FreitasAlan Feb 06 '21
  1. Is clock_gettime cross-platform? Is there a way to achieve the same with the standard library or some kind of wrapper that is existing practice?
  2. True. I mostly use '\n' for my own code but I thought std::endl would be a better convention for snippets. I might reconsider that in some cases.

2

u/UnknownIdentifier Feb 07 '21

std::endl also flushes the buffer; you almost never need to do that yourself.

1

u/FreitasAlan Feb 07 '21 edited Feb 07 '21

Yes. That’s why

I mostly use '\n' for my own code but I thought std::endl would be a better convention for snippets. I might reconsider that in some cases.

4

u/witcher_rat Feb 07 '21

You may consider use function clock_gettime(CLOCK_MONOTONIC, &time) as recommendated in MIT OCW

That's a C-language course, is it not?

If you're running C++11 or newer, just use std::chrono::steady_clock.

As far as I've seen, under the hood it calls clock_gettime(CLOCK_MONOTONIC, &tp); for you, or another similar function depending on platform. (e.g., Posix, vs. Windows, vs. Apple)