How to get system time in C++?

2020-07-20 13:26发布

In fact i am trying to calculate the time a function takes to complete in my program. So i am using the logic to get system time when i call the function and time when the function returns a value then by subtracting the values i get time it took to complete. So if anyone can tell me some better approach or just how to get system time at an instance it would be quite a help

标签: c++
5条回答
\"骚年 ilove
2楼-- · 2020-07-20 13:30

In some system you don't have access to the time.h header. Therefore, you can use the following code snippet to find out how long does it take for your program to run, with the accuracy of seconds.

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;



}
查看更多
你好瞎i
3楼-- · 2020-07-20 13:46

Under Linux, try gettimeofday() for microsecond resolution, or clock_gettime() for nanosecond resolution.

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

查看更多
走好不送
4楼-- · 2020-07-20 13:47

You can use time_t

查看更多
兄弟一词,经得起流年.
5楼-- · 2020-07-20 13:50

The approach I use when timing my code is the time() function. It returns a single numeric value to you representing the epoch which makes the subtraction part easier for calculation.

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;
}

Keep in mind this is user time. For CPU, time see Ben's reply.

查看更多
对你真心纯属浪费
6楼-- · 2020-07-20 13:51

Your question is totally dependant on WHICH system you are using. Each system has its own functions for getting the current time. For finding out how long the system has been running, you'd want to access one of the "high resolution performance counters". If you don't use a performance counter, you are usually limited to microsecond accuracy (or worse) which is almost useless in profiling the speed of a function.

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

If you're coding under a platform other than windows, just google performance counter and the system you are coding under, and it should tell you how you can access the counter.

Edit (clarification)
This is c++, just include windows.h and import the "Kernel32.lib" (seems to have removed my hyperlink, check out the documentation at: http://msdn.microsoft.com/en-us/library/ms644904.aspx). For C#, you can use the "System.Diagnostics.PerformanceCounter" class.

查看更多
登录 后发表回答