How to get system time in C ++?

Actually, I am trying to calculate the time that the function takes to complete in my program. So I use logic to get the system time when I call the function and the time when the function returns a value, and then subtracting the values ​​that I get to complete this. Therefore, if someone can tell me some better approach or just get the system time in the instance, it will be very useful

+3
source share
5 answers

Your question depends entirely on the WHICH system you are using. Each system has its own functions for obtaining the current time. To find out how long the system has been running, you need to access one of the "high resolution performance counters". If you do not use a performance counter, you are usually limited by the accuracy of microseconds (or worse), which is practically useless when profiling the speed of a function.

On Windows, you can access the counter using the QueryPerformanceCounter () function. This returns an arbitrary number that is different on each processor. To find out how many ticks are in the counter == 1 second, call "QueryPerformanceFrequency ()".

If you are coding under a platform other than Windows, it’s just a Google performance counter and the system you are coding on, and it should tell you how you can access the counter.

Change (clarification)
This is C ++, just turn on windows.h and import "Kernel32.lib" (it seems they deleted my hyperlink, see the documentation at: http://msdn.microsoft.com/en-us/library/ms644904.aspx ). For C # you can use the "System.Diagnostics.PerformanceCounter" class.

+3
source

The approach I use when the time of my code is the time () function. It returns you a single numeric value representing an era , which makes it easy to calculate the subtraction part.

Relevant Code:

#include <time.h> #include <iostream> int main (int argc, char *argv[]) { int startTime, endTime, totalTime; startTime = time(NULL); /* relevant code to benchmark in here */ endTime = time(NULL); totalTime = endTime - startTime; std::cout << "Runtime: " << totalTime << " seconds."; return 0; } 

Remember that this is user time. For CPU time, see Ben's answer.

+5
source

You can use time_t

+1
source

On Linux, try gettimeofday() to resolve microseconds or clock_gettime() to resolve nanoseconds.

(Of course, the actual clock may have a rougher resolution.)

0
source

On some system, you do not have access to the time.h header. Therefore, you can use the following code snippet to find out how long it takes to run your program to the nearest second.

 void function() { time_t currentTime; time(&currentTime); int startTime = currentTime; /* Your program starts from here */ time(&currentTime); int timeElapsed = currentTime - startTime; cout<<"It took "<<timeElapsed<<" seconds to run the program"<<endl; } 
0
source

All Articles