Yoric
Yoric

Reputation: 4083

How do I find on which CPU/core I'm running?

For benchmarking purposes, I'm using rdtsc to determine how much pseudo-time I have spent executing some chunks of code inside a critical loop. Since my code can be rescheduled between processes at any moment, I would like to minimize the noise by just dumping the data if I find out that I have changed CPU between the start and the stop of the micro-measure.

Is there an x86 instruction I could use to identify on which CPU/core I'm running? Something that would give me either a unique identifier, or a CPU# and a core#, etc.

Apparently, cpuid doesn't provide the information anymore, so I'm looking for an alternative.

Upvotes: 3

Views: 964

Answers (1)

ab.
ab.

Reputation: 345

Not really. You don't really want a separate instruction, since your thread could have been migrated to another core immediately after executing the instruction and before you could do anything useful with its result (or between the RDTSC and the "what core am I on?" check). RDTSCP conveniently avoids this, because it both delivers the TSC and returns whatever the OS told it to in a single instruction, but it requires OS support and is a serialising instruction (so more heavyweight than RDTSC, which may affect fine-grained timing measurements).

As someone noted in the comments, if the precision of every measurement is important to you, you probably need to use an OS API to pin the thread to ensure it doesn't migrate. Alternatively, migration will be relatively rare, so if you can take enough measurements, then the occasional outliers that it causes will be obvious and easy to exclude.

Upvotes: 1

Related Questions