1

I have finished writing a function and I want to compare time and cpu execution of the function with other function. This is code to calculate time execution but I not sure it accuracy. Do you have accuracy code to calculate time and cpu spending for one function in C++?

//Only time execution. CPU spending? #include "stdafx.h" #include <iostream> #include <time.h> using namespace std; int _tmain(int argc, _TCHAR* argv[]) { clock_t start, end; start = clock(); for(int i=0;i<65536;i++) cout<<i<<endl; end = clock(); cout << "Time required for execution: " << (double)(end-start)/CLOCKS_PER_SEC << " seconds." << "\n\n"; return 0; } 
3

3 Answers 3

6

In C++11 you should use std::chrono::high_resolution_clock which under the hood uses the clock source with the smallest tick period provided by the system:

#include <chrono> auto start = std::chrono::high_resolution_clock::now(); //... auto end = std::chrono::high_resolution_clock::now(); auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end - start); 
Sign up to request clarification or add additional context in comments.

4 Comments

Sorry. I am using visual studio C++ 2010 . What is library that your code need include ?
@user2408476: I'm afraid I don't know how well Visual Studio supports C++11 features. If including <chrono> doesn't work, you may want either to use boost which provides a high_resolution_clock implementation, or Mats Petersson's QueryPerformanceCounter solution.
<chrono> is not supported in VC++2010. For high precision time measurements you should use QueryPerformanceCounter.
Is this the CPU time or computer time ?
1

For this particular code, I'm pretty sure your code is quite OK.

For short periods, you may need to use more precise timing functions, such as Windows' QueryPerformanceCounter and QueryPerformanceFrequency to get higher precision timing.

Comments

1

The easiest way I know of to get precise time estimates is to use an OpenMP function:

#include <stdio.h> #include <omp.h> int main() { double dtime = omp_get_wtime(); foo(); dtime = omp_get_wtime() - dtime; printf("time in seconds %f\n", dtime); } 

In gcc compile with -fopenmp. In visual studio turn on OpenMP support under C++/Language Support. BTW, OpenMP now works in Visual Studio 2012 express. For CPU time profiling you can try http://developer.amd.com/tools-and-sdks/heterogeneous-computing/amd-codeanalyst-performance-analyzer/

2 Comments

it's quite absurd to measure time with a parallelization suite, but well: it works.
Why is it absurd? The solution is cross platform, simple, accurate, and even works with threading. What's not to like?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.