srand(clock()) in c++? I used to do a course in c++.In that particular course i faced with this problem.But i dont know what is the real meaning of this function in c++?
-
C++ inherits the C standard library. Try ``man srand`` ... Not sure what you mean by "clock" are you referring to ``std::chrono::*_clock``? – rmccabe3701 Jun 10 '18 at 04:53
-
1@rmccabe3701 OP refers more likely to `clock` from `
` header. – Daniel Langr Jun 10 '18 at 04:58 -
Note that `rand` (and therefore `srand` as well) is quite deprecated. Use `
` starting from C++11 instead. – Daniel Langr Jun 10 '18 at 05:01
2 Answers
srand is a function defined in the C standard library, and it sets the Random number generator to a certain start seed.
What a random number generator does to generate subsequence numbers, is it takes the current input and applies some calculation based upon the current value.
All future rand() calls with a given known start seed can are actually deterministic. This is why it is called "Pseudo-random number generator".
So if for example, you started your program each time, with srand(100) -- and outputted rand() multiple times -- your entire output of each run would be identical.
Now what clock() function does, is it takes in the current time in milliseconds, and uses that as a start seed.
Since current time is something that is constantly changing, and milliseconds of the current time is not something easily to determine what it is at the precise time that the operation clock() is called, -- it is a sort of good way to get a "random" start seed.
EDIT
clock() actually gives back the processor time consumed by the program.
You can have a look at How to get current timestamp in milliseconds since 1970 just the way Java gets
You need to be a bit careful with time_t time (time_t* timer) defined in "time.h" as it is not portable across platforms.
This srand, and rand functions are however not recommended, and are deprecated in C++11, which defines random class. You can have a look here: http://en.cppreference.com/w/cpp/numeric/random

- 514
- 5
- 19
Why we can use srand(clock())? Because,
- srand initializes the random number sequence.
- Don't want the same result each time in a simulation.
Clock returns the processor time consumed by the program.
The value returned is expressed in clock ticks.
Fine grained and different when main()starts running.

- 49,595
- 11
- 110
- 380

- 15
- 1
- 7