I have a function that if you plug a number into it it counts them out. It only does this if you call the function at the begining of the program meaning it has something to do with clock(). I added clock() to the rest of my variables but the function doesnt count. Specifically at the if statement.
code:
#include <stdio.h>
#include <string>
#include <iostream>
#include <stdlib.h>
#include <windows.h>
#include "math.h"
#include <time.h>
#include <ctime>
#include <cstdlib>
#include <mmsystem.h>
void countbysec(int Seconds);
using namespace std;
int main(){
int secondsinput;
cout<<"Type how many seconds to cout \n";
cin>>secondsinput;
countbysec(secondsinput);
return 0;
}
void countbysec(int Seconds){
clock_t Timer;
Timer = clock() + Seconds * CLOCKS_PER_SEC ;
clock_t counttime = clock() + (Timer / Seconds);
clock_t secondcount = 0;
while(clock() <= Timer){
if(clock() == counttime){
counttime = counttime + CLOCKS_PER_SEC;
secondcount = secondcount + 1;
cout<<secondcount<<endl;
}
}
}
You're not calling the function with this line:
void countbysec(int Seconds);
You're forward declaring the function. The compiler needs to see the declaration of the function before you can call it otherwise you'll see:
error: use of undeclared identifier 'countbysec'
It needs to be able to type check and generate the code for the call at the point you make the call.
You could declare and define the function in one step by moving the code block from below main() to above it in your file. This is normal C/C++ behaviour.
First, clock is not the right tool to do what it looks like you want. It returns an approximation of how much CPU time has been used by the process. Approximation should have a few alarm bells ringing. Next, time CPU time is not the same as wall time, so who can say just how much elapsed time went by while the program worked its way to ten seconds.
So
if(clock() == counttime){
The time must be EXACTLY counttime in order to do your count-incrementing. The odds of pulling this off are not too good. You might shoot past it. And if you do, nothing will ever be counted. I recommend
if(clock() >= counttime){
Next, you are unlikely to get that last second because
while(clock() <= Timer)
Probably trips first and exits the loop.
If you want to count seconds, look to something like std::this_thread::sleep_until.
Set Wake time = current time + 1 second, then
Sleep until Wake time,
count,
Add a second onto Wake time,
repeat until done.
Related
I was given the following HomeWork assignment,
Write a program to test on your computer how long it takes to do
nlogn, n2, n5, 2n, and n! additions for n=5, 10, 15, 20.
I have written a piece of code but all the time I am getting the time of execution 0. Can anyone help me out with it? Thanks
#include <iostream>
#include <cmath>
#include <ctime>
using namespace std;
int main()
{
float n=20;
time_t start, end, diff;
start = time (NULL);
cout<<(n*log(n))*(n*n)*(pow(n,5))*(pow(2,n))<<endl;
end= time(NULL);
diff = difftime (end,start);
cout <<diff<<endl;
return 0;
}
better than time() with second-precision is to use a milliseconds precision.
a portable way is e.g.
int main(){
clock_t start, end;
double msecs;
start = clock();
/* any stuff here ... */
end = clock();
msecs = ((double) (end - start)) * 1000 / CLOCKS_PER_SEC;
return 0;
}
Execute each calculation thousands of times, in a loop, so that you can overcome the low resolution of time and obtain meaningful results. Remember to divide by the number of iterations when reporting results.
This is not particularly accurate but that probably does not matter for this assignment.
At least on Unix-like systems, time() only gives you 1-second granularity, so it's not useful for timing things that take a very short amount of time (unless you execute them many times in a loop). Take a look at the gettimeofday() function, which gives you the current time with microsecond resolution. Or consider using clock(), which measure CPU time rather than wall-clock time.
Your code is executed too fast to be detected by time function returning the number of seconds elapsed since 00:00 hours, Jan 1, 1970 UTC.
Try to use this piece of code:
inline long getCurrentTime() {
timeb timebstr;
ftime( &timebstr );
return (long)(timebstr.time)*1000 + timebstr.millitm;
}
To use it you have to include sys/timeb.h.
Actually the better practice is to repeat your calculations in the loop to get more precise results.
You will probably have to find a more precise platform-specific timer such as the Windows High Performance Timer. You may also (very likely) find that your compiler optimizes or removes almost all of your code.
I have found the usleep function in unistd.h, and I thought it was useful to wait some time before every action.But I have discovered that the thread just sleeps if it it doesn't receive any signal.For example if I press a button (I'm using OpenGL but the question is more specific about time.h and unistd.h), the thread gets awaken and I'm not getting what I want.
In time.h there is the sleep function that accepts an integer but an integer is too much ( I want to wait 0.3 seconds), so I use usleep.
I ask if there is a function to take time in milliseconds (from any GNU or whatever library).
It should work like time(), but returning milliseconds instead of seconds.Is that possibile?
If you have boost you can do it this way:
#include <boost/thread.hpp>
int main()
{
boost::this_thread::sleep(boost::posix_time::millisec(2000));
return 0;
}
This simple example, as you can see in the code, sleeps for 2000ms.
Edit:
Ok, I thought I understood the question but then I read the comments and now I'm not so sure anymore.
Perhaps you want to get how many milliseconds that has passed since some point/event? If that is the case then you could do something like:
#include <boost/chrono.hpp>
#include <boost/thread.hpp>
#include <iostream>
int main()
{
boost::chrono::high_resolution_clock::time_point start = boost::chrono::high_resolution_clock::now();
boost::this_thread::sleep(boost::posix_time::millisec(2000));
boost::chrono::milliseconds ms = boost::chrono::duration_cast<boost::chrono::milliseconds> (boost::chrono::high_resolution_clock::now() - start);
std::cout << "2000ms sleep took " << ms.count() << "ms " << "\n";
return 0;
}
(Please excuse the long lines)
This is a cross-platform function I use:
unsigned Util::getTickCount()
{
#ifdef WINDOWS
return GetTickCount();
#else
struct timeval tv;
gettimeofday(&tv, 0);
return unsigned((tv.tv_sec * 1000) + (tv.tv_usec / 1000));
#endif
}
This is a sample pgm to check the functionality of Sleep() function.This is a demo only since iam using this sleep() and clock() functions in my app developement.
// TestTicks.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include<iostream>
#include<iomanip>
#include <Windows.h>
int _tmain(int argc, _TCHAR* argv[])
{
int i, i2;
i = clock();
//std::cout<<" \nTime before Sleep() : "<<i;
Sleep(30000);
i2 = clock();
//std::cout<<" \nTime After Sleep() : "<<i2;
std::cout<<"\n Diff : "<<i2 -i;
getchar();
return 0;
}
in this code i am calculating the time using clock() before and after the sleep function.
Since iam using sleep(30000), the time diff would be atleast 30000.
I have run this prgm many times. and printed output as 30000, 30001, 30002. These are ok. But some times i am getting values like 29999 and 29997.How this possible, since i put 30000 sleep b/w the clock().
Please give me the reason for this.
According to http://msdn.microsoft.com/en-us/library/windows/desktop/ms686298(v=vs.85).aspx:
The system clock "ticks" at a constant rate. If dwMilliseconds is less than the resolution of the system clock, the thread may sleep for less than the specified length of time. If dwMilliseconds is greater than one tick but less than two, the wait can be anywhere between one and two ticks, and so on.
It just means that the Sleep function will never sleep exactly for the amount of time given, but as close as possible given the resolution of the scheduler.
The same page gives you a method to increase the timer resolution if you really need it.
There are also high resolution timers that may better fit your needs.
Unless you're using a realtime OS, that is very much expected.
The Operating System has to schedule and run many other processes, so waking yours' up may not match the exact time you wanted to sleep.
The clock() function tells how much processor time the calling process has used.
You may replace the use of clock() by the function GetSystemTimeAsFileTime
in order to measure the time more accurately.
Also you may try to use timeBeginPeriod with wPeriodMin returned by a call to timeGetDevCaps in order to obtail maximum interrupt frequency.
In order to synchronize the sleeps with the system interrupt period, I'd also suggest
to have a sleep(1) ahead of the first "time capture".
By doing so, the "too shorts" will disappear.
More information abount sleep can be found here
#include <iostream>
#include <time.h>
void wait(int seconds)
{
int endwait;
endwait = clock() + seconds * CLOCKS_PER_SEC ;
while (clock() < endwait){}
}
int main()
{
wait(2);
cout<<"2 seconds have passed";
}
I was given the following HomeWork assignment,
Write a program to test on your computer how long it takes to do
nlogn, n2, n5, 2n, and n! additions for n=5, 10, 15, 20.
I have written a piece of code but all the time I am getting the time of execution 0. Can anyone help me out with it? Thanks
#include <iostream>
#include <cmath>
#include <ctime>
using namespace std;
int main()
{
float n=20;
time_t start, end, diff;
start = time (NULL);
cout<<(n*log(n))*(n*n)*(pow(n,5))*(pow(2,n))<<endl;
end= time(NULL);
diff = difftime (end,start);
cout <<diff<<endl;
return 0;
}
better than time() with second-precision is to use a milliseconds precision.
a portable way is e.g.
int main(){
clock_t start, end;
double msecs;
start = clock();
/* any stuff here ... */
end = clock();
msecs = ((double) (end - start)) * 1000 / CLOCKS_PER_SEC;
return 0;
}
Execute each calculation thousands of times, in a loop, so that you can overcome the low resolution of time and obtain meaningful results. Remember to divide by the number of iterations when reporting results.
This is not particularly accurate but that probably does not matter for this assignment.
At least on Unix-like systems, time() only gives you 1-second granularity, so it's not useful for timing things that take a very short amount of time (unless you execute them many times in a loop). Take a look at the gettimeofday() function, which gives you the current time with microsecond resolution. Or consider using clock(), which measure CPU time rather than wall-clock time.
Your code is executed too fast to be detected by time function returning the number of seconds elapsed since 00:00 hours, Jan 1, 1970 UTC.
Try to use this piece of code:
inline long getCurrentTime() {
timeb timebstr;
ftime( &timebstr );
return (long)(timebstr.time)*1000 + timebstr.millitm;
}
To use it you have to include sys/timeb.h.
Actually the better practice is to repeat your calculations in the loop to get more precise results.
You will probably have to find a more precise platform-specific timer such as the Windows High Performance Timer. You may also (very likely) find that your compiler optimizes or removes almost all of your code.
I am writing a program that will be used on a Solaris machine. I need a way of keeping track of how many seconds has passed since the start of the program. I'm talking very simple here. For example I would have an int seconds = 0; but how would I go about updating the seconds variable as each second passes?
It seems that some of the various time functions that I've looked at only work on Windows machines, so I'm just not sure.
Any suggestions would be appreciated.
Thanks for your time.
A very simple method:
#include <time.h>
time_t start = time(0);
double seconds_since_start = difftime( time(0), start);
The main drawback to this is that you have to poll for the updates. You'll need platform support or some other lib/framework to do this on an event basis.
Use std::chrono.
#include <chrono>
#include <iostream>
int main(int argc, char *argv[])
{
auto start_time = std::chrono::high_resolution_clock::now();
auto current_time = std::chrono::high_resolution_clock::now();
std::cout << "Program has been running for " << std::chrono::duration_cast<std::chrono::seconds>(current_time - start_time).count() << " seconds" << std::endl;
return 0;
}
If you only need a resolution of seconds, then std::steady_clock should be sufficient.
You are approaching it backwards. Instead of having a variable you have to worry about updating every second, just initialize a variable on program start with the current time, and then whenever you need to know how many seconds have elapsed, you subtract the now current time from that initial time. Much less overhead that way, and no need to nurse some timing related variable update.
#include <stdio.h>
#include <time.h>
#include <windows.h>
using namespace std;
void wait ( int seconds );
int main ()
{
time_t start, end;
double diff;
time (&start); //useful call
for (int i=0;i<10;i++) //this loop is useless, just to pass some time.
{
printf ("%s\n", ctime(&start));
wait(1);
}
time (&end);//useful call
diff = difftime(end,start);//this will give you time spent between those two calls.
printf("difference in seconds=%f",diff); //convert secs as u like
system("pause");
return 0;
}
void wait ( int seconds )
{
clock_t endwait;
endwait = clock () + seconds * CLOCKS_PER_SEC ;
while (clock() < endwait) {}
}
this should work fine on solaris/unix also, just remove win refs
You just need to store the date/time when application started. Whenever you need to display for how long your program is running get current date/time and subtract the when application started.