Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
name: build-and-test

on:
push:
pull_request:
workflow_dispatch:

jobs:
build-test:
name: ${{ matrix.os }}
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, windows-latest, macos-latest]

steps:
- name: Checkout
uses: actions/checkout@v6

- name: Build and test (Linux)
if: runner.os == 'Linux'
run: |
make check
make benchmark
./benchmark

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is the purpose of | tee /dev/stderr | grep -qx PASSED to get the exit code right? If so, we should probably enhance Makefile so that make check gives the right exit code directly, if it doesn't already.

Similarly, doesn't make check already build and run benchmark? Do we end up running it twice here?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is the purpose of | tee /dev/stderr | grep -qx PASSED to get the exit code right?

Yes, and I just fixed the makefile to produce correct error code

Similarly, doesn't make check already build and run benchmark?

It doesn't, I just checked and still we need to run make check , make benchmark and ./benchmark ( for powershell script build.ps1 -Target benchmark does run benchmark.exe though


# Apple's clang doesn't accept -march=native on arm64 and doesn't bundle
# OpenMP, so override CFLAGS/LDFLAGS and skip benchmark.
- name: Build and test (macOS)
if: runner.os == 'macOS'
run: make check CFLAGS="-Wall -O2 -fomit-frame-pointer" LDFLAGS=""

- name: Build and test (Windows)
if: runner.os == 'Windows'
shell: powershell
run: |
.\build.ps1 -Target check
.\build.ps1 -Target benchmark
16 changes: 16 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# Build artifacts (Unix Makefile)
*.o
/tests
/phc-test
/initrom
/userom

# Build artifacts (MSVC / build.ps1)
*.obj
*.exe
*.pdb
*.ilk

# Test output
TESTS-OUT
PHC-TEST-OUT
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ all: $(PROJ)
check: tests
@echo 'Running tests'
@time ./tests | tee TESTS-OUT
@diff -U0 TESTS-OK TESTS-OUT && echo PASSED || echo FAILED
@diff -U0 TESTS-OK TESTS-OUT && echo PASSED || { echo FAILED; exit 1; }

ref:
$(MAKE) $(PROJ) OBJS_CORE=yespower-ref.o
Expand Down
14 changes: 14 additions & 0 deletions README
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,20 @@ word "PASSED".
We do most of our testing on Linux systems with gcc. The supplied
Makefile assumes that you use gcc.

On Windows.

A PowerShell script, build.ps1, is provided to build yespower with the
MSVC toolchain. It requires Visual Studio Community 2026 with the
"Desktop development with C++" workload installed (this also provides
vswhere.exe, which the script uses to locate the compiler automatically).
From a PowerShell prompt in this directory, run:

powershell -ExecutionPolicy Bypass -File .\build.ps1 -Target check

This builds and runs tests.exe and prints "PASSED" on success. Other
targets mirror the Makefile: "all" (default), "tests", "benchmark",
"ref", "check-ref", and "clean".


Alternate code versions and make targets.

Expand Down
59 changes: 57 additions & 2 deletions benchmark.c
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,63 @@
#include <stdio.h>
#include <stdlib.h> /* for atoi() */
#include <string.h>
#include <unistd.h>
#include <time.h>
#ifndef _MSC_VER
#include <unistd.h>
#include <sys/times.h>
#include <sched.h>
#else
/*
* MSVC lacks the POSIX <unistd.h>, <sys/times.h> and <sched.h> interfaces used
* below. Provide a minimal shim implemented on top of the Win32 API so that
* benchmark.c builds and the single-threaded benchmark works. The optional
* OpenMP multi-threaded section is only compiled when _OPENMP is defined, which
* build.ps1 does not enable for MSVC.
*/
#include <windows.h>

struct tms {
clock_t tms_utime;
clock_t tms_stime;
clock_t tms_cutime;
clock_t tms_cstime;
};

#define _SC_CLK_TCK 1

/* Report a 1 ms tick so wall- and CPU-times share the same units. */
static long sysconf(int name)
{
(void)name;
return 1000;
}

/* 100 ns FILETIME units -> 1 ms ticks. */
static clock_t filetime_to_ticks(const FILETIME *ft)
{
ULARGE_INTEGER t;
t.LowPart = ft->dwLowDateTime;
t.HighPart = ft->dwHighDateTime;
return (clock_t)(t.QuadPart / 10000);
}

/* Wall-clock as return value (1 ms ticks), process CPU times in *buf. */
static clock_t times(struct tms *buf)
{
FILETIME creation, exit, kernel, user;
LARGE_INTEGER freq, now;

GetProcessTimes(GetCurrentProcess(), &creation, &exit, &kernel, &user);
buf->tms_utime = filetime_to_ticks(&user);
buf->tms_stime = filetime_to_ticks(&kernel);
buf->tms_cutime = 0;
buf->tms_cstime = 0;

QueryPerformanceFrequency(&freq);
QueryPerformanceCounter(&now);
return (clock_t)(now.QuadPart * 1000 / freq.QuadPart);
}
#endif

#include "yespower.h"

Expand Down Expand Up @@ -138,6 +191,7 @@ int main(int argc, const char * const *argv)
count * clk_tck / (end_v - start_v),
count, (double)(end - start) / clk_tck);

#ifdef _OPENMP
for (i = 0; i < nsave; i++) {
unsigned int j;
for (j = i + 1; j < nsave; j++) {
Expand All @@ -149,7 +203,6 @@ int main(int argc, const char * const *argv)
}
}

#ifdef _OPENMP
unsigned int nt = omp_get_max_threads();

printf("Benchmarking %u thread%s ...\n",
Expand All @@ -171,6 +224,7 @@ int main(int argc, const char * const *argv)

unsigned long long count1 = count, count_restart = 0;

#ifdef SCHED_RR
if (!geteuid()) {
puts("Running as root, so trying to set SCHED_RR");
#pragma omp parallel
Expand All @@ -180,6 +234,7 @@ int main(int argc, const char * const *argv)
perror("sched_setscheduler");
}
}
#endif

start = times(&start_tms);

Expand Down
214 changes: 214 additions & 0 deletions build.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,214 @@
#requires -Version 5.1
<#
.COPYRIGHT
Copyright 2013-2026 Alexander Peslyak
Copyright 2026 CPUchain
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.

.SYNOPSIS
Build yespower with the MSVC toolchain (port of the supplied GNU Makefile).
Comment thread
quadcpu marked this conversation as resolved.

.DESCRIPTION
Locates a Visual Studio / Build Tools installation with the C++ compiler
using vswhere.exe, imports its x64 environment, and compiles the yespower
"tests" and "benchmark" programs with cl.exe / link.exe.

Targets (mirroring the Makefile):
build.ps1 # build tests.exe and benchmark.exe (optimized)
build.ps1 -Target check # build and run tests.exe, diff against TESTS-OK
build.ps1 -Target benchmark # build and run benchmark.exe
build.ps1 -Target ref # build using the reference implementation
build.ps1 -Target check-ref
build.ps1 -Target clean # remove build artifacts

.NOTES
Requires Visual Studio 2026 (Community is fine) with the
"Desktop development with C++" workload installed. See the README section
"How to test yespower for proper operation." for details.
#>
[CmdletBinding()]
param(
[ValidateSet('all', 'tests', 'benchmark', 'check', 'ref', 'check-ref', 'clean')]
[string]$Target = 'all'
)

$ErrorActionPreference = 'Stop'
Set-Location -LiteralPath $PSScriptRoot

# --- Toolchain detection via vswhere.exe ------------------------------------

function Find-VsWhere {
$candidates = @(
(Join-Path ${env:ProgramFiles(x86)} 'Microsoft Visual Studio\Installer\vswhere.exe'),
(Join-Path $env:ProgramFiles 'Microsoft Visual Studio\Installer\vswhere.exe')
)
foreach ($c in $candidates) {
if ($c -and (Test-Path -LiteralPath $c)) { return $c }
}
$cmd = Get-Command vswhere.exe -ErrorAction SilentlyContinue
if ($cmd) { return $cmd.Source }
throw "vswhere.exe not found. Install Visual Studio 2026 (it ships vswhere)."
}

function Get-VcVarsPath {
$vswhere = Find-VsWhere
# Require the x64/x86 C++ compiler toolset.
$installPath = & $vswhere -latest -products * `
-requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 `
-property installationPath
if (-not $installPath) {
throw "No Visual Studio installation with the C++ toolset was found. " +
"Install the 'Desktop development with C++' workload."
}
$vcvars = Join-Path $installPath 'VC\Auxiliary\Build\vcvars64.bat'
if (-not (Test-Path -LiteralPath $vcvars)) {
throw "vcvars64.bat not found under '$installPath'."
}
return $vcvars
}

# Import the MSVC x64 environment (PATH, INCLUDE, LIB, ...) into this session.
function Import-VcEnvironment {
$vcvars = Get-VcVarsPath
Write-Host "Using MSVC environment: $vcvars"
$marker = '___VCVARS_ENV___'
# vcvars64.bat may emit benign stderr noise; don't let it abort the script.
$lines = & cmd /c "`"$vcvars`" 2>nul && echo $marker && set"
$seen = $false
foreach ($line in $lines) {
if (-not $seen) {
if ($line.Trim() -eq $marker) { $seen = $true }
continue
}
if ($line -match '^([^=]+)=(.*)$') {
Set-Item -Path ("Env:" + $matches[1]) -Value $matches[2]
}
}
if (-not $seen) { throw "Failed to import the MSVC environment." }
}

# --- Compiler / linker settings (port of Makefile CFLAGS/LDFLAGS) -----------

# /O2 -> -O2
# /D__SSE2__ -> enable the SSE2 intrinsic code path (MSVC x64 supports
# <emmintrin.h>; this path is free of GCC inline asm).
# /DUSE_OPENMP -> intentionally NOT set: benchmark.c's OpenMP section relies
# on POSIX-only APIs and VLAs that MSVC cannot build.
$CFLAGS = @('/nologo', '/O2', '/MT', '/D__SSE2__', '/wd4146', '/wd4244')

$OBJS_COMMON = @('sha256.obj')
$OBJS_CORE_OPT = 'yespower-opt.obj'
$OBJS_CORE_REF = 'yespower-ref.obj'

function Invoke-Tool {
param([string]$Exe, [string[]]$Arguments)
Write-Host ">> $Exe $($Arguments -join ' ')"
# Send tool output to the host so it doesn't pollute function return values.
& $Exe @Arguments | Out-Host
if ($LASTEXITCODE -ne 0) {
throw "$Exe failed with exit code $LASTEXITCODE"
}
}

function Compile-One {
param([string]$Source, [string[]]$ExtraFlags = @())
$obj = [System.IO.Path]::GetFileNameWithoutExtension($Source) + '.obj'
Invoke-Tool 'cl' (@('/c') + $CFLAGS + $ExtraFlags + @("/Fo$obj", $Source))
return $obj
}

function Link-Exe {
param([string]$Out, [string[]]$Objs)
Invoke-Tool 'link' (@('/nologo', "/OUT:$Out") + $Objs)
}

function Build-Tests {
param([string]$Core = $OBJS_CORE_OPT)
$coreSrc = if ($Core -eq $OBJS_CORE_REF) { 'yespower-ref.c' } else { 'yespower-opt.c' }
$objs = @()
$objs += Compile-One $coreSrc
$objs += Compile-One 'sha256.c'
$objs += Compile-One 'tests.c'
Link-Exe 'tests.exe' $objs
Write-Host "Built tests.exe"
}

function Build-Benchmark {
param([string]$Core = $OBJS_CORE_OPT)
$coreSrc = if ($Core -eq $OBJS_CORE_REF) { 'yespower-ref.c' } else { 'yespower-opt.c' }
$objs = @()
$objs += Compile-One $coreSrc
$objs += Compile-One 'sha256.c'
$objs += Compile-One 'benchmark.c'
Link-Exe 'benchmark.exe' $objs
Write-Host "Built benchmark.exe"
}

function Invoke-Benchmark {
param([string]$Core = $OBJS_CORE_OPT)
Build-Benchmark -Core $Core
Write-Host 'Running benchmark'
& .\benchmark.exe | Out-Host
if ($LASTEXITCODE -ne 0) { throw "benchmark.exe failed with exit code $LASTEXITCODE" }
}

function Invoke-Check {
param([string]$Core = $OBJS_CORE_OPT)
Build-Tests -Core $Core
Write-Host 'Running tests'
& .\tests.exe | Out-File -Encoding ascii -FilePath 'TESTS-OUT'
if ($LASTEXITCODE -ne 0) { throw "tests.exe failed with exit code $LASTEXITCODE" }
# Compare against the reference output, ignoring CRLF/LF differences.
$expected = (Get-Content -Raw 'TESTS-OK') -replace "`r`n", "`n"
$actual = (Get-Content -Raw 'TESTS-OUT') -replace "`r`n", "`n"
if ($expected.TrimEnd("`n") -eq $actual.TrimEnd("`n")) {
Write-Host 'PASSED' -ForegroundColor Green
} else {
Write-Host 'FAILED' -ForegroundColor Red
Compare-Object ($expected -split "`n") ($actual -split "`n") |
Format-Table -AutoSize | Out-String | Write-Host
exit 1
}
}

function Invoke-Clean {
$patterns = @('*.obj', 'tests.exe', 'benchmark.exe', 'TESTS-OUT',
'*.ilk', '*.pdb', '_probe*', '_run.ps1', '_vcout.txt')
foreach ($p in $patterns) {
Get-ChildItem -LiteralPath $PSScriptRoot -Filter $p -ErrorAction SilentlyContinue |
Remove-Item -Force -ErrorAction SilentlyContinue
}
Write-Host 'Cleaned build artifacts.'
}

# --- Dispatch ---------------------------------------------------------------

switch ($Target) {
'clean' { Invoke-Clean; break }
default {
Import-VcEnvironment
switch ($Target) {
'all' { Build-Tests; Build-Benchmark }
'tests' { Build-Tests }
'benchmark' { Invoke-Benchmark }
'check' { Invoke-Check }
'ref' { Build-Tests -Core $OBJS_CORE_REF; Build-Benchmark -Core $OBJS_CORE_REF }
'check-ref' { Invoke-Check -Core $OBJS_CORE_REF }
}
}
}
Loading