kaan_atakan
kaan_atakan

Reputation: 4057

How to get the processor core number on which the script is running on a linux system with PHP (similar to sched_getcpu() in C)

I would like to know which processor core my php process is running on. It seems possible to do this in C like so:

#include <sched.h>
#include <stdio.h>

void main() {
    printf("The CPU Number is: %d", sched_getcpu());
}

Does anyone know of an existing wrapper for PHP?

Upvotes: 0

Views: 177

Answers (1)

jordanvrtanoski
jordanvrtanoski

Reputation: 5557

Yes it is. Apart from the obvious answer that you can compile the C example and use it in PHP either as an external call, or as a library trough FFI, there is a simpler way by using the ps shell utility. The psr column of the ps report will tell you on which cpu the process is running. Combined it with the -p to get the cpu for a specific pid, use getmypid() to find your pid.

When you put all together as a function getmycpu() it will looks like this:

<?php
function getmycpu() {
    $mypid = getmypid();
    $cpucore = (int)shell_exec("ps -o psr= -p $mypid");
    return $cpucore;
}
?>

Now you can use the function to get the core on which the process is running

<?php
$output = getmycpu();
echo "You are running on cpu #$output", PHP_EOL;
?>

Upvotes: 1

Related Questions