Counting cores in .Net and Java

As C# and Visual Basic (in the .Net world) and Java are high level programming languages, most developers were not used to check for some hardware information. With multicore microprocessors and a task-oriented programming model, trying to take full advantage of parallel processing capabilities offered by modern microprocessors, this is changing.

I'm preparing a sequence of posts related to fine-grained parallelism with .Net Parallel Extensions. However, as I've received this questions dozens of times in my e-mail, I thought it was a good idea to post the answer for these three programming languages.

Why do you need to know the number of logical cores? Because taking this information into account, you can decide at run-time, the number of parallel tasks that you're going to run concurrently.
If you discover that you have four cores available, you can run four tasks concurrently. This changes if you run the same application on a dual-core microprocessor.

And what about eight logical cores, like the ones offered by a Core i7. A quad-core microprocessor that offers eight logical cores via Intel's Hyper-Threading Technology.

.Net 4.0 with Parallel Extensions will offer many excellent features to decide the number of logical cores to dedicate to each parallelized task. Java 7 will also offer similar features with its fork-join framework. However, you must begin with the most simple task: counting the number of logical cores.
Just a single line of code for each programming language. It is very easy.


Visual Basic:


These lines return the number of logical cores on Windows and in other operating systems.

For example, if you run these lines on a computer with a quad-core Core i7 supporting Hyper-Threading, it will return 8.
If you run these lines on a computer with a quad-core Q6700, it will return 4.

I know it's a very simple post. However, you have to know these if you are creating applications in these programming languages.
Para obtener más información sobre las optimizaciones del compilador, consulte el aviso sobre la optimización.