How can one deduce the amount of processors a linux os has by using elapsed time(time it takes to execute any section of code).I have the clock ticks it took to perform a particular section of code .How do i measure the amount of cores on the machine from that
-
1By elapse time? I don't think so. Or perhaps I've misunderstood your question. It would be useful if you can elaborate further. – Shawn Chin Feb 05 '13 at 09:17
-
2What's wrong with *nproc* command? – KBart Feb 05 '13 at 09:17
-
Elapsed time could be defined as the number of time it takes to execute a particular amount of code – Jack welch Feb 05 '13 at 09:30
-
2The elapsed time (both *wall* time and *cpu* time) depend on a lot of additional things, including processor speed, features, architecture, compiler optimizations and so on. Unless you own a crystal ball you can't use it to determine the number of cores. – scai Feb 05 '13 at 09:39
2 Answers
You can get the information about CPU(No of processors & no of cores,etc) using
cat /proc/cpuinfo
.
but if you are trying to calculate the clock ticks taken in executing particular code inside linux-kernel you can try.
#include <sys/time.h>
unsigned long ini,end;
preempt_disable();
rdtscl(ini);
...your code....
rdtscl(end);
preempt_enable();
printk("time lapse in cpu clics: %lu\n",(end-ini));
for more details http://www.xml.com/ldd/chapter/book/ch06.html or download.intel.com/embedded/software/IA/324264.pdf and if your code is taking more time then you can also use jiffies effectively.
And for user-space application you can use various timing functions which give the time in nanosecond resolution or oprofile(http://oprofile.sourceforge.net/about/) & refer Timer function to provide time in nano seconds using C++
-
@KBart Elapsed time is the amount of time it takes to execute any amount of code. – Jack welch Feb 05 '13 at 09:31
-
I know what it is, what I don’t know is how to calculate number of cores based on that. P.S. negative vote removed as @akp has expanded his answer. – KBart Feb 05 '13 at 10:48
-
@akp the first part of my comment was the answer to Jack welch, just forgot to add his name. Sorry for inconvenience. – KBart Feb 05 '13 at 11:07
I guess we could do something like this:
Write some code that does some heavy math work, that can be run in parallel - such as a naive method for finding primes. Then run that in multiple threads, starting with one, then going up. At some point, the time it takes to figure out the N first primes will be, the number of threads will be the same as the number of (available) processor cores.
But it's a very clumsy method to find the number of processors, and it almost certainly won't work on a system with high load, or a system that is running on a virtual machine, etc, etc.

- 126,704
- 14
- 140
- 227