You are here:

C++/call CPU Time

Advertisement


Question
QUESTION: Hello,
What is the command for calling CPU TIME in C++?

ANSWER: Amir, the functions on windows are QueryPerformanceCounter to get ticks,
and QueryPerformanceFrequency to get the frequency in ticks per second.

---------- FOLLOW-UP ----------

QUESTION: How can I use that to find how much time it takes to run my program? (I want to know the time of running process)

Answer
Amir, here is some sample code.

#include "Windows.h"

typedef unsigned __int64 PC_t;

PC_t PerfCounterFreq(void)
{
  static PC_t result = 0;
  if (result == 0)
  {
     LARGE_INTEGER li;
     QueryPerformanceFrequency(&li);
     result = (PC_t)li.QuadPart;
  }
  return result;
}

PC_t PerfCounter(void)
{
   LARGE_INTEGER result;
   QueryPerformanceCounter(&result);
   return (PC_t)result.QuadPart;
}

double ElapsedMs(PC_t start)
{
   return double(PerfCounter() - start)/PerfCounterFreq()*1000.0;
}

double ElapsedMs(PC_t earlier, PC_t later)
{
   PC_t diff;
   diff = (earlier < later) ? (later - earlier) : (earlier - later);
   return double(diff)/PerfCounterFreq()*1000.0;
}


#include <iostream>
using namespace std;

int main(void)
{
  PC_t start;
  PC_t end;
  double ms;

  start = PerfCounter();
  Sleep(1000);
  ms = ElapsedMs(start);
  cout << "That took " << ms << " ms.\n";


  start = PerfCounter();
  Sleep(1); // This will take about 10 to 15 milliseconds
  end = PerfCounter();
  ms = ElapsedMs(start, end);
  cout << "That took " << ms << " ms.\n";

  return 0;
}  

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Zlatko

Expertise

No longer taking questions.

Experience

No longer taking questions.

Education/Credentials
No longer taking questions.

©2012 About.com, a part of The New York Times Company. All rights reserved.