Skip to content
Open
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
10 changes: 10 additions & 0 deletions skiplang/prelude/runtime/runtime32_specific.c
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,16 @@ uint64_t SKIP_time_ms() {
return (((uint64_t)hi) << 32) | ((uint64_t)lo);
}

uint64_t SKIP_time_ns() {
// No nanosecond precision on 32-bit/WASM; fall back to milliseconds * 1e6.
return SKIP_time_ms() * 1000000;
}

void SKIP_sleep_ms(uint64_t ms) {
// Not implemented on 32-bit/WASM.
(void)ms;
}

void SKIP_flush_stdout() {
// Not implemented
}
Expand Down
12 changes: 12 additions & 0 deletions skiplang/prelude/runtime/runtime64_specific.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ extern "C" {
#include <map>
#include <random>
#include <string>
#include <thread>
#include <vector>

extern "C" {
Expand Down Expand Up @@ -442,6 +443,17 @@ uint64_t SKIP_time_ms() {
.count();
}

uint64_t SKIP_time_ns() {
using namespace std::chrono;

return duration_cast<nanoseconds>(steady_clock::now().time_since_epoch())
.count();
}

void SKIP_sleep_ms(uint64_t ms) {
std::this_thread::sleep_for(std::chrono::milliseconds(ms));
}

char* SKIP_unix_strftime(char* formatp, char* timep) {
struct tm* tm = (struct tm*)timep;
char buffer[1024];
Expand Down
11 changes: 11 additions & 0 deletions skiplang/prelude/src/stdlib/other/Time.sk
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,17 @@ native fun time(): Int;
@cpp_extern("SKIP_time_ms")
native fun time_ms(): Int;

// Current time in nanoseconds from a monotonic clock (steady_clock).
// Suitable for measuring elapsed time, not wall-clock time.
@debug
@cpp_extern("SKIP_time_ns")
native fun time_ns(): Int;

// Sleep for the given number of milliseconds.
@debug
@cpp_extern("SKIP_sleep_ms")
native fun sleep_ms(ms: Int): void;

@cpp_extern("SKIP_strftime")
native fun strftime(format: String, timestamp: Int): String;

Expand Down
18 changes: 18 additions & 0 deletions skiplang/prelude/tests/skfs/TestRuntime.sk
Original file line number Diff line number Diff line change
Expand Up @@ -151,4 +151,22 @@ fun testRuntime(): void {
);
}

@test
fun testTimeNs(): void {
t1 = Time.time_ns();
SKTest.expectTrue(t1 > 0, "time_ns: returns positive value");
t2 = Time.time_ns();
SKTest.expectTrue(t2 >= t1, "time_ns: monotonically non-decreasing");
}

@test
fun testSleepMs(): void {
before = Time.time_ns();
Time.sleep_ms(1);
after = Time.time_ns();
elapsed = after - before;
SKTest.expectTrue(elapsed > 1000000, "sleep_ms: slept at least 1ms");
SKTest.expectTrue(elapsed < 10000000, "sleep_ms: slept less than 10ms");
}

module end;