How to accurately measure the runtime of a C ++ program with small input data

Dear forum members!
I have seen some discussion on how to measure the running time of a C ++ program on my forum, but the input data must be large enough.
Can you help me to measure the running time of a C ++ program with small input data.
For example, a simple command is to print the string "cplusplus" to the screen, I want to measure its running time (although it is very very small).

This is a timepiece program for your screen, write by CodeBlock:
1
2
3
4
5
6
7
8
9
10
#include <iostream>
#include <iomanip>
#include <ctime>

int main ()
{
    float t = clock();
    std::cout<<"cplusplus"<<" printed in the screen during the time "
    <<std::setprecision(20)<<(clock()-t)/1000<< "s";
}

The result I get is always 0s, despite the exact 20-digit formatting in the output.

I look forward to receiving the explanation, suggestions to solve this problem. Thank you sincerely for your help!
Last edited on
Measure the elapsed processor time when the operation is repeated a large number of times; estimate the time for one operation from the result.

For example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <ctime>
#include <iomanip>

int main()
{
    const int NTIMES = 1'000'000'000 ;
    volatile double d = 0 ;

    const auto start = std::clock() ;
    for( int i = 0 ; i < NTIMES ; ++i ) d += 0.5 ;
    const auto end = std::clock() ;

    std::cout << std::fixed << std::setprecision(2)
              << ( (end-start) * 1.0e9 / CLOCKS_PER_SEC ) / NTIMES
              << " nanoseconds per (volatile double) +=\n" ;
} 

clang++ -std=c++14 -stdlib=libc++ -O3 -Wall -Wextra -pedantic-errors main.cpp -lsupc++ && ./a.out
4.67 nanoseconds per (volatile double) += 

http://coliru.stacked-crooked.com/a/8d627cd0ca35469c
Sincerely thank you!
You have a very smart way, which I did not think of...
Topic archived. No new replies allowed.