How to calculate how many milliseconds it takes to run my program?

This will show how many seconds:

#include <iostream> #include <time.h> using namespace std; int main(void) { int times,timed; times=time(NULL); //CODE HERE timed=time(NULL); times=timed-times; cout << "time from start to end" << times; } 

This will show how many ticks:

 #include <iostream> #include <time.h> using namespace std; int main(void) { int times,timed; times=clock(); //CODE HERE timed=clock(); times=timed-times; cout << "ticks from start to end" << times; } 

How to get milliseconds?

+5
source share
6 answers

Refer to the question " Convert the difference between 2 times in milliseconds " for stack overflow.

Or use this:

 static double diffclock(clock_t clock1,clock_t clock2) { double diffticks=clock1-clock2; double diffms=(diffticks)/(CLOCKS_PER_SEC/1000); return diffms; } 
+10
source

If you are using a Unix OS such as Linux or Mac OS X , you can go to the command line and use the line

 time call-program 

A time command shows how long it takes to execute any command line and tells you about it.

I don’t know if there is something similar for Windows, and how you can measure milliseconds inside a C / C ++ program.

+6
source

There is a macro CLOCKS_PER_SEC that helps you convert ticks to milliseconds.

There are O / S-specific APIs for obtaining high-resolution timers.

You can run your program more than once (for example, 1000 times) and measure it with a low-resolution timer (for example, a few seconds), and then divide this amount by the number of times you ran it to get (a higher permissions).

+3
source

On Windows, you can use GetTickCount , which is in milliseconds.

+2
source

In Win32, you can access the high-resolution timer using QueryPerformanceFrequency and QueryPerformanceCounter (IMHO, which should be preferred, possibly with a departure from GetTickCount ). You can find an example in the "Community Content" section on MSDN.

+1
source

This will show how many ticks:

 #include <iostream> #include <time.h> using namespace std; int main(void) { int times,timed; times=clock(); //CODE HERE timed=clock(); times=timed-times; cout << "ticks from start to end" << times; } 

How to get milliseconds?

clock() returns milliseconds. Compile this code, it will return 1000. Of course, if you are using Linux, not Windows, replace #include <windows.h> with #include <unistd.h> and replace Sleep(1000) with usleep(1000000) .

 #include <stdio.h> #include <time.h> #include <windows.h> int main() { unsigned long x = clock(); Sleep(1000); printf("Difference: %d", clock() - x); } 
0
source

All Articles