c++ timers

Is this a good way to use timers in c++ for all platforms? or is there a better alternative, I ask this because I'm trying to find an accurate and cross platform solution for measuring time on all machines that run at different speeds,and preferably measured in milliseconds.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <iostream>
#include <ctime>
#include <chrono>
#include <cstdlib>
#include <string>
#include <ctime>
using namespace std::chrono;

///Timer
high_resolution_clock::time_point lastTicks;
high_resolution_clock::time_point currentTicks;

void StartTimer()
{
    lastTicks = high_resolution_clock::now();
}
double GetTimer()
{
    currentTicks = high_resolution_clock::now();
    duration<double> timeCount = duration_cast<duration<double>>(currentTicks - lastTicks);
    return timeCount.count();;
}

//Generates random number from range min to max.
unsigned int RandomRange(unsigned int min,unsigned int max)
{
    static unsigned int randomizer = max;
    randomizer += max;
    srand(time(0)*randomizer);
    return min + rand()%(max-min);
}
int main()
{
    StartTimer();

    std::cout<<"Testing RandomRange() functions speed"<<std::endl;
    for(int i = 0; i < 10000; i++)
    {
        std::cout<<RandomRange(0,200)<<std::endl;
    }

    std::cout<<"Done!"<<std::endl;
    std::cout<<"Execution of this code took "<<GetTimer()<<" seconds. "         <<std::endl;
    std::cin.get();
    return 0;
}
Last edited on
It is okay way to measure wall clock, but your method or measuring execution time is bad:
1) high_resolution_clock is a wall clock, that means it measures time in real world, not time spent on current process: if, for example, OS will pause this program execution to give CPU time for other program (this is how multitasking works), your calculation will be wrong. Use clock() function;
2) Your code does not test RandomRange function speed, but console output speed. Console output is slow, any time spent by RandomRange will be within standard error for output time and therefore unmeasureable.

3) RandomRange is itself bad: it is very predictable and not really random as you explicitely set seed on each iteration and not even bother to warm-up generator. Why not use proper C++11 random facilities?
Thank you for your reply that helped allot concerning the use of time functions in c++. And yes my random number generator is bad I'm still yet to learn how to use c++11 random generator engines and I'm fully aware of Cout being a slow function,just wanted random numbers to be printed :).

what I really needed to know was if this was good for measuring real time for all operating systems and machines in c++,I've been lost on this for a little while now.So thanks again

Topic archived. No new replies allowed.