This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
The C clock() function just returns a zero
I ran the following code to test the working of clock() function. I work on ubuntu 12.04.
#include <stdio.h>
#include <time.h>
#include <iostream>
using namespace std;
double diffclock(clock_t clock1,clock_t clock2)
{
double diffticks=clock1-clock2;
double diffms=(diffticks*10)/CLOCKS_PER_SEC;
return diffms;
}
int main()
{
string name;
int i;
clock_t begin=clock();
cout << "Hi what is your name? ";
getline(cin, name);
clock_t end=clock();
cout << "Time elapsed: " << double(diffclock(end,begin)) << " ms"<< endl;
return 0;
}
But no matter how much time i take to write my name, the time elapsed is always shown as 0ms.
Can you tell me what is the problem?
clock() returns the number of ticks USED SINCE THE PROGRAM STARTED executing. There is no need (in this specific) example to get the clock_t begin value.
Try printing out both the begin and end values and see what they are. They're likely both 0 or close to 0 as waiting for user input doesn't use CPU time.
Either way, I recommend the time() function as you don't need tick precision.
http://www.cplusplus.com/reference/clibrary/ctime/time/
I think you should be using the time() function. Here is how it works: http://asust.in/007D
You just call it and it returns the number of seconds since Unix epoch (January 1, 1970).
The clock() function returns the number of clock ticks since the program started. Here: http://asust.in/007E
Related
I am making a timer to calculate the number of seconds until the user presses 3 however the program doesn't work, and no value is saved in the integer variable 'sec'.
where am i wrong?
I have include windows.h and ctime.h
Here's the code:
void func(){
int sec=0
cout<<"Press 3 to end Timer";
cin>>t;
while(t!=3){
Sleep(1);
sec++;}
if(t==3)
{
cout<<"Timer ended";
}
}
This is because cin >> t is blocking. That is, execution doesn't move to your while-loop until the input is complete.
Something like this would work:
#include <chrono>
// This is just to make the example cleaner.
using namespace chrono;
...
system_clock::time_point startTime = system_clock::now();
cin >> t;
system_clock::time_point endTime = system_clock::now();
milliseconds duration = time_point_cast<milliseconds>(endTime - startTime);
At this point, duration.count() is the number of milliseconds spent waiting for input. You can do some math to turn it into seconds, or you could use seconds instead like this:
seconds duration = time_point_cast<seconds>(endTime - startTime);
but in this case, 2.9 seconds will show up as 2 seconds (I think). So I'd do this to output it:
cout << "Duration: " << (double)duration.count() / 1000.0 << endl;
Or something along those lines. I'm typing this raw, so there might be typos.
I wrote the following program in C++ to measure how much time it will take to print to the default output stream in different ways:
#include <algorithm>
#include <chrono>
#include <iostream>
using namespace std;
using namespace std::chrono;
int main() {
// Get starting timepoint
auto start = high_resolution_clock::now();
for (int i=0;i<100000;i++)
{
cout << "Hello";
}
// Get ending timepoint
auto stop = high_resolution_clock::now();
// Get duration. Substart timepoints to
// get durarion. To cast it to proper unit
// use duration cast method
auto duration = duration_cast<microseconds>(stop - start);
cout << "Time taken by function: "
<< duration.count() << " microseconds" << endl;
return 0;
}
At the first round I ran it with: cout << "Hello" << endl; and it took 147,570 microseconds.
At the second round I rant it with: cout << "Hello\n"; and took 128,543 microseconds.
Lastly, I ran it with: printf("Hello\n"); and it took 121,223 microseconds.
What caused this noticeable difference?
Note: I took the average from 10 tests for each one.
By default, cin/cout waste time synchronizing themselves with the C library’s stdio buffers, so that you can freely intermix calls to scanf/printf with operations on cin/cout.
Turn this off with
std::ios_base::sync_with_stdio(false);
Also many C++ tutorials tell you to write cout << endl instead of cout << '\n'. But endl is actually slower because it forces a flush, which is usually unnecessary. (You’d need to flush if you were writing, say, an interactive progress bar, but not when writing a million lines of data.) Write '\n' instead of endl.
Also as C++ is object-oriented , cin and cout are objects and hence the overall time is increased due to object binding.
So, a simple one liner, "std::ios_base::sync_with_stdio(false);" could make cin/cout faster than printf/scanf.
Hope this helps you
Anything in an OOP will be slower than the equivalent in a purely functional language like C. OOP comes with a price for object binding.
internal syncing / flushing in is what normally slows down iostream i/o in this case, Furthur, Actual times also vary from compiler to compiler.
Using scanf() in C++ programs is faster than using cin?
look at this answer for more clarity.
Before I start, here is the code:
#include <iostream>
#include <ctime>
using namespace std;
int main() {
int i = 0;
while (true) {
i++;
cout << i << endl;
clock_t time = clock() + 1000;
while (clock() != time);
}
return 0;
}
So, basically, it works, however, after a little while it just stops counting down but the program is still running. I'm new to C++ programming and I don't know how to fix this. Could somebody help me out?
EDIT: I'm not wondering how to fix my program still running, I'm wondering how to fix it not outputting numbers at one point randomly.
while (clock() != time);
If you overshoot time, which is very likely given how quickly clock() increments, you'll be stuck in that loop forever.
Use <= instead, so that any greater value of clock() will break the loop.
As an aside, busy-waiting is so 1970. You should prefer a "timed wait" of some kind that blocks until a duration has elapsed.
I am trying to time a code I've got in C++. I have an inner and an outer loop that I want to time separately, but at the same time. For some reason when I do this one of the instances returns 1.84467e+13 and always this exact number.
Why is this happening?
Here is a minimum working example that replicates the effect on my machine:
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
int main()
{
long int i, j;
clock_t start, finish, tick, tock;
double a = 0.0;
double adding_time, runtime;
start = clock();
for(i=0; i<10; i++)
{
a=0.0;
tick =clock();
for(j=0; j<10000000; j++)
{
a+=1;
}
tock= clock();
adding_time = (double)(tick - tock)/CLOCKS_PER_SEC;
cout << "Computation time:" << adding_time << endl;
}
finish = clock();
runtime = (double)(finish - start)/CLOCKS_PER_SEC;
cout << "Total computation time:" << runtime << endl;
}
Your clock_t is apparently an unsigned 64-bit type.
You're taking tick - tock, where tock was measured after tick, so if there's any difference between the two at all, it's going to try to produce a negative number--but since it's an unsigned type, that's wrapping around to become something close to the largest number that can be represented in that type.
Obviously, you really want to use tock-tick instead.
let say tic = 2ms and tac is 4ms; so when you do tic-tac(2-4) that will generate a negative number obviously.. even if it given a positive number it wont be the real time. and also, the number it generate (which doesnt appear on my computer) is a big number, so, try to use the manipulator;
#include"iomanip"
cout << fixed << showpoint;
cout << setprecision(2);
it might work..
I was trying to program a Timer class (unaware that boost had one), then when that wasn't working, I tried to just output the value of clock(), using this code:
#include <ctime>
#include <iostream>
int main()
{
for(int i = 0; i < 50; ++i)
{
std::cout << std::clock() << " ";
}
return 0;
}
When I run the program, I get a series of 0s. I have a similar experience when using boost thread sleep functions to spread out timing a little longer (although after a few seconds, it jumps from 0 to 10,000 and keeps outputting 10,000).
I'm running Gentoo Linux. Is this a platform thing? A C++ thing? What's going on?
Edit: Strangely the jump to 10000 comes after a number of seconds, not milliseconds. When I was sleeping my thread for a second at a time, it took five or six seconds to get to 10000. However, if I'm understanding correctly. The time the thread spends sleeping doesn't contribute towards the clock() count? (Which would make sense; why would it be executing clock cycles if it's sleeping?)
The clock() return value is specified in microseconds. But typical granularity of whatever low-level system call the clock() implementation uses is much lower. So it seems that on your system the granularity is 10ms. Also note that clock() does NOT measure real time - it measures CPU time used by the program. So the time flows when your program controls the CPU, and it freezes when your program is suspended - sleeping, for example.
std::clock's resolution is unspecified. In most cases, it's resolution is going to be about 10ms. Hence the jump.
Try the following:
#include <ctime>
#include <iostream>
int main()
{
for(int i = 0; i < 50; ++i)
{
for (int j = 0; j < 500; ++j )
{
std::cout << j << " ";
}
std::cout << std::endl;
std::cout << std::clock() << std::endl;
}
std::cout << std::endl;
return 0;
}
On my system, I see the return value of clock() staying at 0 until at some point it jumps to 10000. It stays at 10000 till the end. If I remove the std::cout in the inner loop, the return value of clock() stays at 0 all the way through. Looks like clock() returns values in increments of 10000 only.
If I change the inner loop to compute the square root of j and print the return value of sqrt(), the return value of clock() goes up to 50000, but is still increases in increments of 10000.
on my 64 bit operating system the CLOCKS_PER_SEC speed is 1000.and the values of clock comes in milliseconds. perfect timing will be extracted from the code below.
int main(){
clock_t a,b;
int c,d,e,f;
c=clock();
scanf("%d",&e);
d=clock();
f=(d-c)/CLOCKS_PER_SECOND;
printf("timing is %d seconds",f);/*for 64 bit operating system
CLOCKS_PER_SECOND is 1000*/
}