std::time(0) performance
I was wondering what the performance implications are of using std::time(0) to seed开发者_StackOverflow社区 random number generators. I assume that it's a system call (if not please correct me), which generally isn't the best option regarding performance. Assuming std::time(0) is used many times throughout a program, will there be severe performance implications if any?
P.S. I'm more curious than anything, as currently there aren't any performance issues.
Reseeding the RNG should be a rather rare event, so I don't think you need to be concerned about performance. If you are reseeding frequently enough to cause a performance issue, you might want to rethink your approach -- you may be doing more harm than good.
My old probability/statistics professor would tell you that if you seed your random generator more than once, you're doing it wrong. It doesn't get better when seeded again and again. It get worse! If that was for cryptographic applications it would be a major weakness, and even if it's not, there's no reason to.
So in short, yes, it's a system call, but you should only seed once, so it's completely absorbed in the rest of the computations.
No, you shouldn't see any performance issues doing this, even if you call time(0)
frequently (note that its resolution is generally in seconds, though, so there's not much reason to call it more than once per second for using it for your purpose).
If it does look like it is causing performance problems, something is very, very wrong.
You typically only need to seed a random generator occasionally (usually only once), so it shouldn't be an issue.
To satisfy your curiosity, I'd like to point out that std::time()
is usually a system call. However, I do know that in some cases, the OS may use approximations based on something like the hardware clock-tick counter (rdtsc
instruction on x86) if the last call was executed recently. This is very efficient in the expected case, and IMHO it's not any less accurate, given that avoiding a system call results in much more deterministic behavior.
But yeah, re-seeding your RNG shouldn't ever be the bottleneck in your application.
精彩评论