Ferenz
Ferenz

Reputation: 39

Measure time with same result

I want to measure time (very precisely in milliseconds) and start another thread (totally 4) at some time. I tried it with:

double Time()
{
    duration = (std::clock() - start);
    return duration;
}

//...

start = std::clock();
while (Time() < 1000)
{
    //Start thread...
    //...
}

It works, but in every experiment I recived diffrent result (small difference). Its even possible? Does depends how many programs runs in background (It slows down my computer)? So if it possible what should I use? Thanks

(sorry for my English)

Upvotes: 1

Views: 66

Answers (1)

mksteve
mksteve

Reputation: 13085

The operating system runs in quanta - little chunks of processing which are are below our level of perception.

Within a single quantum, the CPU should act reasonably stably. If your task will use more than one quantum of time, then the operating system will be free to use slices of times for other tasks.

Using a condition variable You can notify_all to wake up any waiting threads.

So start the number of threads, but before they are measured and start working have them waiting on a condition_variable. Then when the condition_variable notify_all the threads will be runnable. If they are started at the same time, you should get synchronized stable results.

Variance occurs.

  1. Not scheduled - the cores on your CPU are doing other things, so 1 or more thread misses the quantum
  2. Blocked on IO. If you need to interact with the disk, that can cause blocks until data is available.
  3. Blocked in mutex - if they are modifying a shared resource, the wait for the resource becoming free adds time.
  4. Cache behavior some operations cause the cache of all the CPUs to be flushed, this will affect the performance of all the threads.
  5. Whether data is in the cache or not the CPU runs faster from L1 cache, than from main memory. If the threads read the same data, they will help each other cause the data to be cached, and run at the same (ish) speed.

Upvotes: 1

Related Questions