title: How to measure the time a mutex waits before being acquired?
body: <p>I'm not sure the question is easily understandable, so I'll start with a (faulty) code of what I would like to do.</p>
  
  <pre><code>...
  {
      Time start = getCurrentTime();
      scoped_lock&lt;MutexType&gt; lock(mutex);
      Time lockWait = getCurrentTime() - start;
  
      // Protected section
      ...
  }
  </code></pre>
  
  <p>This code does not work because nothing guarantees that the thread will not be preempted somewhere between the start time save instruction and the mutex lock, in which case the computed lockWait would be wrong (overestimation).</p>
  
  <p>I can not think of any solution to get around this issue. I feel that I need to get my hands dirty in multithread low level mechanisms, but I do not know how. Would you have any solution or pointer?</p>
  
  <p>So I'm interested in the wait time, obviously, but I also would like to know if the lock is contested or not, which I'm not sure I can obtain with time measurements only. If not, how could I get infos about that?</p>
  
  <p>PS. I've seen there exists some tools that provide some measurements, such as mutrace or even Walgrind, but unfortunately it is required for my measurements to be integrated to the application source code.</p>