Skip to content

Commit

Permalink
Merge pull request #1 from toro01/master
Browse files Browse the repository at this point in the history
Correctly count physical cores on multiple sockets under linux
  • Loading branch information
veddan authored Oct 18, 2016
2 parents 3e4a9bf + 985dec6 commit dfc9726
Showing 1 changed file with 26 additions and 10 deletions.
36 changes: 26 additions & 10 deletions src/main/java/veddan/physicalcores/PhysicalCores.java
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
package veddan.physicalcores;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
Expand All @@ -13,10 +10,15 @@
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
* Static utility class for finding the number of physical CPU cores.
*/
Expand Down Expand Up @@ -84,13 +86,27 @@ private static Integer readFromProc() {
}
try (InputStream in = new FileInputStream(cpuinfo)) {
String s = readToString(in, Charset.forName("UTF-8"));
Set<String> coreIdRows = new HashSet<>();
for (String row : s.split("\n")) {
if (row.startsWith("core id")) {
coreIdRows.add(row);
}
}
return coreIdRows.isEmpty() ? null : coreIdRows.size();
// Count number of different tuples (physical id, core id) to discard hyper threading and multiple sockets
Map<String, Set<String>> physicalIdToCoreId = new HashMap<>();

int coreIdCount = 0;
String[] split = s.split("\n");
String latestPhysicalId = null;
for (String row : split)
if (row.startsWith("physical id")) {
latestPhysicalId = row;
if (physicalIdToCoreId.get(row) == null)
physicalIdToCoreId.put(latestPhysicalId, new HashSet<String>());

} else if (row.startsWith("core id"))
// "physical id" row should always come before "core id" row, so that physicalIdToCoreId should
// not be null here.
physicalIdToCoreId.get(latestPhysicalId).add(row);

for (Set<String> coreIds : physicalIdToCoreId.values())
coreIdCount += coreIds.size();

return coreIdCount;
} catch (SecurityException | IOException e) {
String msg = String.format("Error while reading %s", path);
log.error(msg, e);
Expand Down

0 comments on commit dfc9726

Please sign in to comment.