Jun 21, 2017

[C++] Always consider function thread safeness drags performance in single thread code.

std::cin / std::cout  are thread safe according to CPP ISO (30.2.3 Thread safety),
thus means it's slow in single thread.

Use std::fstream instead.

std::shared_ptr is thread safe for internal ref counting.
That is to say, using std::shared_ptr is slow in single thread as well.
Use _move_ for std::shared_ptr or just using std::unique_ptr.


When running single threaded code, for performance, always think
potential function call is thread safe or not, thus could impact performance.

Ref:

code:

#ifdef __GLIBCXX__
template<typename T>
  using single_threaded_shared_ptr = std::__shared_ptr<T, std::_S_single>;
#else
template<typename T>
  using single_threaded_shared_ptr = std::shared_ptr<T>;
#endif

auto p = std::__make_shared<T, std::_S_single>(args...);

Reference:
https://stackoverflow.com/questions/32317370/avoid-cost-of-stdmutex-when-not-multi-threading
https://stackoverflow.com/questions/3652056/how-efficient-is-locking-an-unlocked-mutex-what-is-the-cost-of-a-mutex
Why is the std::function () operator const?

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.