J
J
JavaSscriptNoob2022-01-22 18:56:48
C++ / C#
JavaSscriptNoob, 2022-01-22 18:56:48

How to accurately calculate how long a cycle takes to complete?

Hello everyone, I'm trying to calculate how long a cycle takes to run on my PC. But the result is always different, can anyone know what this behavior can be connected with?
Here is the code:

#include <iostream>
#include <ctime>


clock_t startTime = clock();
int num = 610000000; // +- 1 sek 
 int  main() {
    for (int i = 0; i < num ; i++) {
        continue;
    };
    clock_t endTime = clock();
    float endTime = 1.0 * (endTime - startTime) / CLOCKS_PER_SEC;
    std::cout << "end time" << endTime ;
    return 0;
}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
Vasily Bannikov, 2022-01-22
@JavaSscriptNoob

1. Depending on the build parameters, this cycle can turn into zero, because it has no side effects (this is the standard
) pause to give CPU time to another program.
3. The frequency of modern processors is not constant, so this can also affect
If you want to write a benchmark, then you need to run the same code several thousand times and calculate at least the average time, and ideally also stddev and stderr

A
Armenian Radio, 2022-01-22
@gbg

Your loop is doing nothing - the compiler has every right to throw it out, so such measurements are meaningless.

R
rPman, 2022-01-22
@rPman

Modern processors with a large number of cores, a complex multi-level caching system in the processor, and multitasking operating systems that do something that users do not really need turn such a simple test into a roulette.
Yes, Armenian Radio correctly said that this particular code is most likely optimized to do nothing, so you need to add at least something or, for example, use a certain global variable marked external as an iterator i (then the compiler will definitely not throw it away and will conscientiously iterate it on one)
On the other hand, why do we need such a test, depending on a bunch of conditions, this loop will look different in assembler and give different results in terms of performance
What can be done with different results - set the affinity for the process to one core and increase the priority, in this case the chances that the process will be evicted will be minimal ... and by the way, turn off the antivirus, that's the process, adds uncertainty to the machine.
ps try to build your example not in msvc but in gcc and/or clang llvm (and even in different win/linux operating systems), the results will surprise you

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question