Add Crystal::System.effective_cpu_count#16148
Add Crystal::System.effective_cpu_count#16148straight-shoota merged 9 commits intocrystal-lang:masterfrom
Crystal::System.effective_cpu_count#16148Conversation
The method is meant to return how many logical CPUs are actually available to the process versus the total number of CPUs from System.cpu_count. Uses the linux specific `sched_getaffinity` syscall.
|
Regarding API design, I think the most relevant information is how many cores are effectively available to the current process. That should be the most straightforward method. I personally prefer different files very much. It might be debatable when there's more shared code, but here it's completely distinct code for different OSes. And we should add a spec for the new API method(s). At least make sure that it generally works. |
|
Win32: # winbase.h
lib LibC
alias DWORD_PTR = ULONG_PTR
fun GetProcessAffinityMask(hProcess : HANDLE, lpProcessAffinityMask : DWORD_PTR*, lpSystemAffinityMask : DWORD_PTR*) : BOOL
end
if LibC.GetProcessAffinityMask(LibC.GetCurrentProcess, out process_affinity, out _) == 0
raise RuntimeError.from_winerror("GetProcessAffinityMask")
end
process_affinity.popcountThis works as long as the process does not opt in to using multiple processor groups, which is relevant when there are more than 64 logical processors present: https://learn.microsoft.com/en-us/windows/win32/procthread/processor-groups |
|
@HertzDevil thank you 🙇 @straight-shoota But the split files don't tell which target use what (which sysconf? which sysctl?) and it becomes awkward to know where to put the linux implementation for the effective cpu count. |
|
Yes, the current file names are not great. |
Co-Authored-By: Quinton Miller <nicetas.c@gmail.com>
Crystal::System.effective_cpu_count (linux)Crystal::System.effective_cpu_count (linux, win32)
Crystal::System.effective_cpu_count (linux, win32)Crystal::System.effective_cpu_count (linux,
Crystal::System.effective_cpu_count (linux, Crystal::System.effective_cpu_count
|
Now with the implementation for all the targets that support it. |
The method is meant to return how many logical CPUs are actually available to the process versus the total number of CPUs from
System.cpu_count.sched_getaffinitysyscallcpuset_getaffinitysysctl(CTL_HW, HW_NCPUONLINEGetProcessAffinityMaskRefactors to have a singleI added yet-another-file 🤷src/crystal/system/unix/cpucount.crfile. There's little point to differentiate BSD from the rest of UNIX for a few lines of code, and it made no sense to put a new linux method on the sysconf file or to create yet-another specific file for one single method.