Get lower value than seconds - c++

I know that time(0) will return in seconds, but is there a way for it to return smaller values? I think they are called miliseconds, but not sure. I need to pass it for srand().
Reason is I made 2 threads communicate with each other, but they communicate so fast, that each second they send like 30 same message to each other and I need those random numbers to be different, so a different seed each "milisecond"

Seems your error is you are trying to call srand() more than once.
See this question for a detailed explaination: srand() -- why call only once?

Assuming you are on a POSIX-compliant environment, you can use gettimeofday
struct timeval tv;
suseconds_t microseconds;
gettimeofday(tv, NULL);
microseconds = tv.tv_usec;

What you are asking is entirely system dependent. In the old days, most systems did time in milliseconds. For example, the VMS operating system used 8-byte times with millisecond increments.
When Unix became popular, libraries started following it by using seconds.
You can get milliseconds on posix as described above.
Apple also has NSDate and CACurrentMediaTime.
Windoze has GetTickCount and some others.

If you need two threads to communicate using pseudo-random numbers, you should use two independent streams, each seeded only once with different random seeds. There are many C/C++ libraries that can do this, but using standard C rand/srand isn't one of them. Even if you correctly call srand() only once, using the same random stream in both threads will cause predictable (i.e. nonrandom) behavior.
Use a better generator, and seed it with some real system randomness--that's /dev/random on real computers, CryptGenRandom on Windows.

There is not standard C/C++ function for this. But usually OS provides such function.
There is function gettimeofday, in Linux.
and there is function GetSystemTime on Windows.
http://linux.die.net/man/2/gettimeofday
http://msdn.microsoft.com/en-us/library/windows/desktop/ms724390(v=vs.85).aspx
maybe there are some other functions....

Related

Is there no equivalent of millis() from Arduino in C++?

I am currently implementing a PID controller for a project I am doing, but I realized I don't know how to ensure a fixed interval for each iteration. I want the PID controller to run at a frequency of 10Hz, but I don't want to use any sleep functions or anything that would otherwise slow down the thread it's running in. I've looked around but I cannot for the life of me find any good topics/functions that simply gives me an accurate measurement of milliseconds. Those that I have found simply uses time_t or clock_t, but time_t only seems to give seconds(?) and clock_t will vary greatly depending on different factors.
Is there any clean and good way to simply see if it's been >= 100 milliseconds since a given point in time in C++? I'm using the Qt5 framework and OpenCV library and the program is running on an ODROID X-2, if that's of any helpful information to anyone.
Thank you for reading, Christian.
I don't know much about the ODROID X-2 platform but if it's at all unixy you may have access to gettimeofday or clock_gettime either one of which would provide a higher resolution clock if available on your hardware.

Portable good precision double timestamp in C++?

Here's what I'd need to do:
double now=getdoubletimestampsomehow();
Where getdoubletimestampsomehow() should be a straight-forward, easy to use function returning a double value representing the number of seconds elapsed from a given date. I'd need it to be quite precise, but I don't really need it to be more precise than a few milliseconds. Portability is quite important, if it isn't possible to directly port it anywhere could you please tell me both an unix and a windows way to do it?
Have you looked at Boost and particularly its Date_Time library ? Here is the seconds since epoch example.
You will be hard-pressed to find something more portable, and of higher resolution.
Portable good precision double timestamp in C++?
There is no portable way to get high-precision timestamp (milliseconds) without using 3rd party libraries. Maximum precision you'll get is 1 second, using time/localtime/gmtime.
If you're fine with 3rd party libraries, use either Boost or Qt 4.
both an unix and a windows way to do it?
GetSystemTime on Windows and gettimeofday on linux.
Please note that if you're planning to use timestamps to determine order of some events, then it might be a bad idea. System clock might have very limited precision (10 milliseconds on windows platform), in which case several operations performed consequently can produce same timestamp. So, to determine order of events you would need "logical timestamps" ("vector clock" is one of examples).
On windows platform, there are highly precise functions that can be used to determine how much time has passed since some point in the past (QueryPerformanceCounter), but they aren't connected to timestamps.
C++11 introduced the <chrono> header containing quite a few portable clocks. The highest resolution clock among them is the std::chrono::high_resolution_clock.
It provides the current time as a std::chrono::time_point object which has a time_since_epoch member. This might contain what you want.
Reference:
Prior to the release of the C++11 standard, there was no standard way in which one could accurately measure the execution time of a piece of code. The programmer was forced to use external libraries like Boost, or routines provided by each operating system.
The C++11 chrono header file provides three standard clocks that could be used for timing one’s code:
system_clock - this is the real-time clock used by the system;
high_resolution_clock - this is a clock with the shortest tick period possible on the current system;
steady_clock - this is a monotonic clock that is guaranteed to never be adjusted.
If you want to measure the time taken by a certain piece of code for execution, you should generally use the steady_clock, which is a monotonic clock that is never adjusted by the system. The other two clocks provided by the chrono header can be occasionally adjusted, so the difference between two consecutive time moments, t0 < t1, is not always positive.
Doubles are not precise - therefore you idea for double now=getdoubletimestampsomehow(); falls down at the first hurdle.
Others have mentioned other possibilities. I would explore those.

How to realise long-term high-resolution timing on windows using C++?

I need to get exact timestamps every couple of ms (20, 30, 40ms) over a long period of time (a couple of hours). The function in which the timestamp is taken is invoked as a callback by a 3rd-party library.
Using GetSystemTime() one can get the correct system timestamp but only with milliseconds accuracy, which is not precise enough for me. Using QueryPerformanceTimer() yields more accurate timestamps but is not synchronous to the system timestamp over a long period of time (see http://msdn.microsoft.com/en-us/magazine/cc163996.aspx).
The solution provided at the site linked above somehow works only on older computers, it hangs while synchronizing when i try to use it with newer computers.
It seems to me like boost is also only working on milliseconds accuracy.
If possible, I'd like to avoid using external libraries, but if there's no other choice I'll go with it.
Any suggestions?
Deleted article from CodeProject, this seems to be the copy: DateTimePrecise C# Class The idea is to use QueryPerformanceCounter API for accurate small increments and periodically adjust it in order to keep long term accuracy. This is about to give microsecond accuracy ("about" because it's still not exactly precise, but still quite usable).
See also: Microsecond resolution timestamps on Windows
Which language are you using?
In Java (1.5 or above) I'd suggest 'System.nanoTime()' which requires no import.
Remember in Windows that time-slice granularity is 1000ms / 64 = 15.625ms.
This will affect inter-process communication, especially on uni-processor machines, or machines that run several heavy CPU usage processes 'concurrently'*.
In fact, I just got DOS 6.22 and Windows for Workgroups 3.11/3.15 via eBay, so I can screenshot the original timeslice configuration for uni-processor Windows machines of the era when I started to get into it. (Although it might not be visible in versions above 3.0).
You'll be hard pressed to find anything better than QueryPerformanceTimer() on Windows.
On modern hardware it uses the HPET as a source which replaces the RTC interrupt controller. I would expect QueryPerformanceTimer() and the System clock to be synchronous.
There is no such QueryPerformanceTimer() on windows. The resource is named QueryPerformanceCounter(). It provides a counter value counting at some higher frequency.
Its incrementing frequency can be retrieved by a call to QueryPerformanceFrequency().
Since this frequency is typically in the MHz range, microsecond resolution can be observed.
There are some implementations around, i.e. this thread or at the Windows Timestamp Project

find c++ execution time

I am curious if there is a build-in function in C++ for measuring the execution time?
I am using Windows at the moment. In Linux it's pretty easy...
The best way on Windows, as far as I know, is to use QueryPerformanceCounter and QueryPerformanceFrequency.
QueryPerformanceCounter(LARGE_INTEGER*) places the performance counter's value into the LARGE_INTEGER passed.
QueryPerformanceFrequency(LARGE_INTEGER*) places the frequency the performance counter is incremented into the LARGE_INTEGER passed.
You can then find the execution time by recording the counter as execution starts, and then recording the counter when execution finishes. Subtract the start from the end to get the counter's change, then divide by the frequency to get the time in seconds.
LARGE_INTEGER start, finish, freq;
QueryPerformanceFrequency(&freq);
QueryPerformanceCounter(&start);
// Do something
QueryPerformanceCounter(&finish);
std::cout << "Execution took "
<< ((finish.QuadPart - start.QuadPart) / (double)freq.QuadPart) << std::endl;
It's pretty easy under Windows too - in fact it's the same function on both std::clock, defined in <ctime>
You can use the Windows API Function GetTickCount() and compare the values at start and end. Resolution is in the 16 ms ballpark. If for some reason you need more fine-grained timings, you'll need to look at QueryPerformanceCounter.
C++ has no built-in functions for high-granularity measuring code execution time, you have to resort to platform-specific code. For Windows try QueryPerformanceCounter: http://msdn.microsoft.com/en-us/library/ms644904(VS.85).aspx
The functions you should use depend on the resolution of timer you need. Some of them give 10ms resolutions. Those functions are easier to use. Others require more work, but give much higher resolution (and might cause you some headaches in some environments. Your dev machine might work fine, though).
http://www.geisswerks.com/ryan/FAQS/timing.html
This articles mentions:
timeGetTime
RDTSC (a processor feature, not an OS feature)
QueryPerformanceCounter
C++ works on many platforms. Why not use something that also works on many platforms, such as the Boost libraries.
Look at the documentation for the Boost Timer Library
I believe that it is a header-only library, which means that it is simple to setup and use...

Getting the System tick count with basic C++?

I essentially want to reconstruct the getTickCount() windows function so I can use it in basic C++ without any non standard libraries or even the STL. (So it complies with the libraries supplied with the Android NDK)
I have looked at
clock()
localtime
time
But I'm still unsure whether it is possible to replicate the getTickCount windows function with the time library.
Can anyone point me in the right direction as to how to do this or even if its possible?
An overview of what I want to do:
I want to be able to calculate how long an application has been "doing" a certain function.
So for example I want to be able to calculate how long the application has been trying to register with a server
I am trying to port it from windows to run on the linux based Android, here is the windows code:
int TimeoutTimer::GetSpentTime() const
{
if (m_On)
{
if (m_Freq>1)
{
unsigned int now;
QueryPerformanceCounter((int*)&now);
return (int)((1000*(now-m_Start))/m_Freq);
}
else
{
return (GetTickCount()-(int)m_Start);
}
}
return -1;
}
On Android NDK you can use the POSIX clock_gettime() call, which is part of libc. This function is where various Android timer calls end up.
For example, java.lang.System.nanoTime() is implemented with:
struct timespec now;
clock_gettime(CLOCK_MONOTONIC, &now);
return (u8)now.tv_sec*1000000000LL + now.tv_nsec;
This example uses the monotonic clock, which is what you want when computing durations. Unlike the wall clock (available through gettimeofday()), it won't skip forward or backward when the device's clock is changed by the network provider.
The Linux man page for clock_gettime() describes the other clocks that may be available, such as the per-thread elapsed CPU time.
clock() works very similarly to Windows's GetTickCount(). The units may be different. GetTickCount() returns milliseconds. clock() returns CLOCKS_PER_SEC ticks per second. Both have a max that will rollover (for Windows, that's about 49.7 days).
GetTickCount() starts at zero when the OS starts. From the docs, it looks like clock() starts when the process does. Thus you can compare times between processes with GetTickCount(), but you probably can't do that with clock().
If you're trying to compute how long something has been happening, within a single process, and you're not worried about rollover:
const clock_t start = clock();
// do stuff here
clock_t now = clock();
clock_t delta = now - start;
double seconds_elapsed = static_cast<double>(delta) / CLOCKS_PER_SEC;
Clarification: There seems to be uncertainty in whether clock() returns elapsed wall time or processor time. The first several references I checked say wall time. For example:
Returns the number of clock ticks elapsed since the program was launched.
which admittedly is a little vague. MSDN is more explicit:
The elapsed wall-clock time since the start of the process....
User darron convinced me to dig deeper, so I found a draft copy of the C standard (ISO/IEC 9899:TC2), and it says:
... returns the implementation’s best approximation to the processor time used ...
I believe every implementation I've ever used gives wall-clock time (which I suppose is an approximation to the processor time used).
Conclusion: If you're trying to time so code so you can benchmark various optimizations, then my answer is appropriate. If you're trying to implement a timeout based on actual wall-clock time, then you have to check your local implementation of clock() or use another function that is documented to give elapsed wall-clock time.
Update: With C++11, there is also the portion of the standard library, which provides a variety of clocks and types to capture times and durations. While standardized and widely available, it's not clear if the Android NDK fully supports yet.
This is platform dependent so you just have to write a wrapper and implement the specifics for each platform.
It's not possible. The C++ standard and, as consequence the standard library, know nothing about processors or 'ticks'. This may or may not change in C++0x with the threading support but at least for now, it's not possible.
Do you have access to a vblank interrupt function (or hblank) on the Android? If so, increment a global, volatile var there for a timer.