Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I want to programme a code in C++ that makes a time-counting at the same time while we are waiting the user to enter for example the integer result we want to see.For instance we want user to enter two integers and select one of the four operations,then write down the result.Meanwhile the clock or the counting machine starts to count the seconds until the user write down the result.
Is it possible to do in C++,if it's not how can I do this?
Thanks...
C++11/14 give you even more efficient ways than the old #include<ctime> headers of C to measure time duration using certain classes like steady_clock, high_resolution_clock, etc defined in the header #include<chrono>. The following code does your job very efficiently:
#include <iostream>
#include <chrono>
using namespace std;
int main()
{
chrono::steady_clock sc; // create an object of `steady_clock` class
auto start = sc.now(); // start timer
// do stuff....
auto end = sc.now(); // end timer (starting & ending is done by measuring the time at the moment the process started & ended respectively)
auto time_span = static_cast<chrono::duration<double>>(end - start); // measure time span between start & end
cout<<"Operation took: "<<time_span.count()<<" seconds !!!";
return 0;
}
The simplest way it to use std::clock_t:
#include <iostream>
#include <cstdio>
#include <ctime>
int main()
{
std::clock_t start;
double duration;
start = std::clock(); // get current time
// Do your stuff here
duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC;
std::cout << "Operation took "<< duration << "seconds" << std::endl;
return 0;
}
There are many ways to do that actually. This one is portable and does not need any extra library to be available. As long as you need second precision, it will be OK.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 months ago.
Improve this question
First thing I tried was system("time"). It gave me the time, but then it asks me for input (???).
I also tried time(NULL), but it gives me the current date as well. I just need the time (hours, minutes, seconds), not the date. I did use <ctime> and tm_sec, tm_min and tm_hour, but I need to use pointers for those, which I'm not allowed to use in this case.
#include <chrono>
#include <iostream>
#include <iomanip>
int main() {
auto time = std::chrono::system_clock::now();
auto asTimeT = std::chrono::system_clock::to_time_t(time); // timestamp since epoch
std::cout << asTimeT << std::endl;
// i don't know what you mean by cannot use pointers.
// std::localtime and std::gmtime return pointers
auto formattedTimeLocal = std::put_time(std::localtime(&asTimeT), "%H:%M:%S"); // HH:MM:SS localtime
std::cout << formattedTimeLocal << std::endl;
auto formattedTimeUtc = std::put_time(std::gmtime(&asTimeT), "%H:%M:%S"); // HH:MM:SS UTC
std::cout << formattedTimeUtc << std::endl;
}
Get current time with std::chrono::system_clock::now()
Convert to time_t which is "the number of seconds (not counting leap seconds) since 00:00, Jan 1 1970 UTC"
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I want to add timer in my game.it works every 30 seconds and after any 30 seconds it should start another 30 seconds.
Every player have 30 sec to play his turn and when it finished he just has 3 pack of 30 seconds to use them for playing his turn.If his packs are finished, it's the turn f another player.
I don't have any idea of it, I don't know how to make timer in c or c++.
If you have boost, boost::asio library provides one solution to the problem. See for example this answer C++ Boost ASIO simple periodic timer?
In addition to the answers above :) if you want a simple handy solution this may help
#include <ctime>
#include <cstdlib>
int main()
{
clock_t startTime = clock(); //Start timer
double secondsPassed;
double secondsToDelay = 30;
std::cout << "Time to delay: " << secondsToDelay << std::endl;
bool flag = true;
while (flag)
{
secondsPassed = (clock() - startTime) / CLOCKS_PER_SEC;
if (secondsPassed >= secondsToDelay)
{
std::cout << secondsPassed << " seconds have passed" << std::endl;
flag = false;
}
}
}
This question already has answers here:
How can I benchmark C code easily?
(5 answers)
Closed 6 years ago.
I have a function which can generate 10000 random numbers and write them in a file.
void generator(char filename[])
{
int i;
int n;
FILE* fp;
if((fp=fopen(filename,"w+"))==NULL)
{
printf("Fail creating fileļ¼");
}
srand((unsigned)time(NULL));
for(i=0;i<10000;i++)
{
n=rand()%10000;
fprintf(fp,"%d ",n);
}
fclose(fp);
}
How can I get the execution time of this function using C/C++ ?
Code profiling is not a particularly easy task (or, as we oft-say in programming, it's "non-trivial".) The issue is because "execution time" measured in seconds isn't particularly accurate or useful.
What you're wanting to do is to measure the number of CPU cycles. This can be done using an external tool such as callgrind (one of Valgrind's tools). There's a 99% chance that's all you want.
If you REALLY want to do that yourself in code, you're undertaking a rather difficult task. I know first hand - I wrote a comparative benchmarking library in C++ for on-the-fly performance testing.
If you really want to go down that road, you can research benchmarking on Intel processors (that mostly carries over to AMD), or whatever processor you've using. However, as I said, that topic is large and in-depth, and far beyond the scope of a StackOverflow answer.
You can use the chrono library;
#include <chrono>
//*****//
auto start = std::chrono::steady_clock::now();
generator("file.txt")
auto end = std::chrono::steady_clock::now();
std::cout << "genarator() took "
<< std::chrono::duration_cast<std::chrono::microseconds>(end - start).count() << "us.\n";
You have already some nice C answers that also work with C++.
Here a native C++ solution using <chrono>:
auto tbegin = std::chrono::high_resolution_clock::now();
...
auto tend = std::chrono::high_resolution_clock::now();
auto tduration = std::chrono::duration_cast<std::chrono::microseconds>(tend - tbegin).count();
The advantage is that you can switch from microsecond to millisecond, seconds or any other time measurement units very easily.
Note that you may have OS limits to the clocking accuracy (typically 15 milliseconds on windows environment), so that this may give meaningful results only if you're really above this limit.
void generator(char filename)
{
clock_t tStart = clock();
/* your code here */
printf("Time taken: %.2fs\n", (double)(clock() - tStart)/CLOCKS_PER_SEC);
}
upd. And add #include <ctime>
Try this
#include <sys/time.h>
struct timeval tpstart,tpend;
double timeuse;
//get time before generator starts
gettimeofday(&tpstart,NULL);
//call generator function
generator(filename);
//get time after generator ends
gettimeofday(&tpend,NULL);
//calculate the used time
timeuse=1000000*(tpend.tv_sec-tpstart.tv_sec)+tpend.tv_usec-tpstart.tv_usec;
timeuse/=1000000;
printf("Used Time:%fsec\n",timeuse);
#include <ctime>
.....
clock_t start = clock();
...//the code you want to get the execution time for
double elapsed_time = static_cast<double>(clock() - start) / CLOCKS_PER_SEC;
std::cout << elapsed_time << std::endl;//elapsed_time now contains the execution time(in seconds) of the code in between
will give you an approximate(not accurate) execution time of the code between the first and second clock() calls
Temporarily make the limit 10000000
Time it with a stopwatch. Divide the time by 1000
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
i just dont understand whats taking so long
its the standard hello world program you write when you first start to learn a new language and its just so un-optimized
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
int main()
{
std::string hello_world = "HELLO WORLD!";
std::string letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ !";
std::vector<long> positions;
std::ostringstream oss;
for(auto l : hello_world){
int position = 0;
position = letters.find(l);
positions.push_back(position);
}
for(long t = 0; t <= 100000000000; t++){
if(t%256465445 == 0){
for(auto p : positions){
oss<<letters[p];
}
}
}
std::cout<<"Hello World!";
}
This seems like it was purposefully un-optimized. I would assume that the time constraints are coming from modding a variable 100,000,000,000 times. But wait, that is not all. Not only do you mod a variable that many times, but when a variable modded to 0, you iterate another 11 times over each char in "Hello World!", or, more precisely, 389 times. That means that the last for loop needs to have done at least 100,000,004,279 calculations. How about you just remove that last for loop, because it seems useless other than to kill time, you'd be better off just doing a sleep(5).
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
In c++:
How can I display the system current time (only time without the date) ?
How can I display current time + 3 minutes?
Can I do it using cout?
Which libraries or functions to use ?
You can try this example (use c++11 clang 3.6):
#include <iostream>
#include <iomanip>
#include <ctime>
#include <chrono>
int main()
{
std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
std::time_t now_c = std::chrono::system_clock::to_time_t(now - std::chrono::hours(24));
std::cout << std::put_time(std::localtime(&now_c), "%T") << std::endl;
std::time_t later_c = std::chrono::system_clock::to_time_t(now - std::chrono::hours(24) + std::chrono::minutes(3));
std::cout << std::put_time(std::localtime(&later_c), "%T") << std::endl;
return 0;
}
just use std::chrono.