Click here to Skip to main content
16,015,827 members
Please Sign up or sign in to vote.
4.50/5 (2 votes)
See more:
Dear All,
I am working on C++ in Linux and I want to find the exact number of cpucycles used my task for execution.But whenever I run my code I get different value of cpucycles.How I can find the exact cpucycles used by my task.Also how I can convert cpucycles to actual execution time.I have also appended my code below.

Thanks in advance
Regards,
Ishtiaq

#include<stdio.h>

static __inline__ unsigned long long rdtsc(void)
{
  unsigned long long int x;
     __asm__ volatile (".byte 0x0f, 0x31" : "=A" (x));
     return x;
}


int main() {
    	unsigned long long cycles = rdtsc(); //1
    	cycles = rdtsc() - cycles;           //2
	
	 
    printf("Time is %d\n", (unsigned)cycles);

    return 0;
}
Posted

You can't find out the exact number of cycles for a number of reasons:
1) The timer isn't fast enough - the minimum interval between two timer "ticks" is greater than the processor cycle time.
2) The execution time will vary depending on what other tasks are running
3) The execution time will vary depending on where your code is, and what it is doing: if it is in the CPU cache(s) entirely, it can run as a very high speed!
 
Share this answer
 
Comments
smishtiaqhussain 10-Jun-11 11:10am    
Thanks for a quick reply.....Will you please tell me that how we can convert cpucycles to time.
see:

http://www.ecrypt.eu.org/ebats/cpucycles.html[^]

If your task is short, then then best thing to do is run it multiple times and take the average elapsed cpucycles.
 
Share this answer
 
Comments
smishtiaqhussain 13-Jun-11 7:47am    
Thanks a lot for your guidance.
It returns different values each time because of what else the system is doing. For example, the OS may be servicing an interrupt, and during this time your process will be suspended for an extremely small amount of time until the OS continues the execution of your program, but this small amount of time (depending on processor speed) could equal many cycles.

To achieve more accurate results, you could write a bootable program which will test your code's speed, this way there will be no OS affecting your code.
 
Share this answer
 
Comments
smishtiaqhussain 13-Jun-11 7:47am    
Thanks a lot for your help.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900