How do I measure time accurately and use random numbers?

I'm in the process of making a game that needs rather accurate time measurement, but I don't know how to measure time. I also need some random numbers, but I don't know the syntax for seeding with srand.
srand(unsigned int);
Generally people seed with
srand(time(NULL));

You'll need to include both <stdlib.h> and <time.h>

http://www.cplusplus.com/reference/clibrary/ctime/

This should have what you need for keeping track of time
Get the time from time.h: http://www.cplusplus.com/reference/clibrary/ctime/

Seed random numbers using the current system time then assign to variables using rand.

1
2
3
4
5
// Seed random number from time
srand (time(NULL));

// Assign a random number to a variable, lets say 1 to 10
int my_int = rand() % 10 + 1;
SFML provides both time and random functionality, amongst a number of other things relevant to game programming.
Here's a simple program that gets the current time and date and prints it out to the console. Feel free to use it for your reference. :)

1
2
3
4
5
6
7
8
9
10
11
12
#include <ctime>
#include <iostream>
using namespace std;

int main()
{
    time_t now(time(false));
    tm *localtm(localtime(&now));
    cout << localtm->tm_hour << ":" << localtm->tm_min << ":" << localtm->tm_sec << endl;
    cout << localtm->tm_mon + 1 << "/" << localtm->tm_mday << "/" << localtm->tm_year + 1900 << endl;
    return 0;
}


The *tm struct has other members you may find of use. Here is a link: http://www.cplusplus.com/reference/clibrary/ctime/tm/

I have heard that the Boost libraries have ways of dealing with time. Here is their official website: http://www.boost.org/
Last edited on
closed account (3hM2Nwbp)
...and if you're using Windows and want to jump right in without worrying about boost library configuration issues: http://www.boostpro.com/download/
Here is my attempt at a timer that counts to 10. It seems to work fine, but why does it only cout integers?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <ctime>

int main ()
{
    clock_t start = clock ();
    clock_t end;

    double elapsedTime = 0;

    while (elapsedTime < 10)
    {
	end = clock ();
	elapsedTime = (end - start) / CLOCKS_PER_SEC;

	std::cout << elapsedTime << std::endl;
    }

    std::cin >> elapsedTime;

    return 0;
}
Why does my code not display decimals when run?
Topic archived. No new replies allowed.