Measuring Elapsed Time and Waiting with Bun.sleep in Bun
In Bun, if you call Bun.nanoseconds() before and after a piece of work and take the difference, you can measure the elapsed time in nanoseconds (billionths of a second). To wait for a fixed amount of time, use await Bun.sleep(ms). Combining the two, I measured that Bun.sleep(100) actually returns after about 100.2 to 100.6 ms.
This post covers how to write benchmarks (comparing which of two approaches is faster) and delays between retries after a failed API call, using only Bun. It also shows measured actual wait times and explains how Bun.sleepSync(), which blocks the whole thread, differs.
The test environment is Ubuntu 24.04 (x86_64, 4 cores, 16 GB memory) with Bun 1.4.4. I ran each script once beforehand and report the results from the second and later runs. The timing values are specific to this environment and may differ on other machines under different load, or on other OSes (macOS, Windows). I did not compare against Node.js process.hrtime.
Bun.nanoseconds() is the time since the process started
According to the official utilities documentation, Bun.nanoseconds() returns the number of nanoseconds since the current bun process started, as a number. I called it on the first line of a script.
// first.ts
const a = Bun.nanoseconds();
const p = performance.now();
console.log(`Bun.nanoseconds(): ${a}`);
console.log(`型: ${typeof a} / 整数か: ${Number.isInteger(a)}`);
console.log(`ミリ秒にすると: ${(a / 1e6).toFixed(3)} ms`);
console.log(`performance.now(): ${p.toFixed(3)} ms`);
$ bun first.ts
Bun.nanoseconds(): 3026476
型: number / 整数か: true
ミリ秒にすると: 3.026 ms
performance.now(): 3.027 ms
At the first line, it was about 3 ms. That is the time from when bun starts until the first line of the script runs. Over three runs, it ranged from 2.3 to 3.2 ms. The value is an integer, and you divide by 1e6 (one million) to convert it to milliseconds. The performance.now() I called right after showed nearly the same value, 3.027 ms.
Since the value itself is the time since startup, when you want the processing time, use the difference between two calls.
Comparing the granularity with Date.now()
Next, I called it one million times and looked at the smallest nonzero difference between consecutive values. I used the same method for performance.now(), and for Date.now() I kept calling it for 50 ms.
// resolution.ts (the Bun.nanoseconds() part)
let minNs = Infinity;
let prev = Bun.nanoseconds();
for (let i = 0; i < 1_000_000; i++) {
const now = Bun.nanoseconds();
if (now !== prev) { minNs = Math.min(minNs, now - prev); }
prev = now;
}
console.log(`Bun.nanoseconds() の最小の刻み: ${minNs} ns`);
| Function | Smallest step in value |
|---|---|
Bun.nanoseconds() |
35 ns |
performance.now() |
41 ns |
Date.now() |
1,000,000 ns (1 ms) |
Date.now() returns integer milliseconds, so work shorter than 1 ms can only come out as 0 or 1. Bun.nanoseconds() shows differences of a few tens of nanoseconds.
The comment in Bun's type definitions (bun.d.ts) says the value is measured with a monotonic system timer. It also notes that number can exactly represent integers only up to Number.MAX_SAFE_INTEGER, so precision degrades if the process keeps running for about 14.8 weeks.
A function to measure processing time
I wrote a function that takes the difference of two Bun.nanoseconds() calls around the work, and I ran the same work five times to get the median.
// bench.ts
function measure(label: string, fn: () => void, runs = 5) {
const times: number[] = [];
for (let i = 0; i < runs; i++) {
const start = Bun.nanoseconds();
fn();
times.push((Bun.nanoseconds() - start) / 1e6);
}
times.sort((a, b) => a - b);
console.log(`${label}: 中央値 ${times[Math.floor(runs / 2)].toFixed(3)} ms(${runs}回)`);
}
const arr = Array.from({ length: 1_000_000 }, (_, i) => i);
measure("for 文で合計", () => { let s = 0; for (let i = 0; i < arr.length; i++) s += arr[i]; });
measure("reduce で合計", () => { arr.reduce((a, b) => a + b, 0); });
measure("JSON.stringify", () => { JSON.stringify(arr); });
$ bun bench.ts
for 文で合計: 中央値 1.106 ms(5回)
reduce で合計: 中央値 1.471 ms(5回)
JSON.stringify: 中央値 15.715 ms(5回)
Summing one million numbers took 1.106 ms with a for loop and 1.471 ms with reduce. Even for work that finishes in around 1 ms, you can compare differences at a resolution finer than 0.1 ms.
Waiting a fixed time with Bun.sleep()
Bun.sleep(ms) returns a Promise that resolves after the given number of milliseconds (official documentation). If you call it with await, execution waits on that line.
I measured the actual wait time with Bun.nanoseconds().
// sleep100.ts
const results: string[] = [];
for (let i = 0; i < 10; i++) {
const start = Bun.nanoseconds();
await Bun.sleep(100);
const ms = (Bun.nanoseconds() - start) / 1e6;
results.push(ms.toFixed(3));
}
console.log(`Bun.sleep(100) を10回: ${results.join(", ")} (ms)`);
$ bun sleep100.ts
Bun.sleep(100) を10回: 100.575, 100.225, 100.247, 100.252, 100.361, 100.278, 100.259, 100.256, 100.283, 101.417 (ms)
All ten runs were longer than 100 ms, and most returned 0.2 to 0.4 ms late. The longest was 101.417 ms. The comment in the type definitions also explains that the specified time is a minimum and the wait may take longer.
I measured 50 runs for each of several durations.
| Specified | Min | Median | Max |
|---|---|---|---|
Bun.sleep(0) |
0.001 ms | 0.001 ms | 0.082 ms |
Bun.sleep(1) |
1.077 ms | 1.103 ms | 1.194 ms |
Bun.sleep(5) |
5.093 ms | 5.146 ms | 5.205 ms |
Bun.sleep(10) |
10.106 ms | 10.169 ms | 10.395 ms |
Bun.sleep(50) |
50.136 ms | 50.200 ms | 54.993 ms |
When I specified 1 ms or more, the median ran about 0.1 to 0.2 ms long (Bun.sleep(0) was nearly 0 ms). However, the maximum for Bun.sleep(50) was 54.993 ms, so it was about 5 ms late at least once. For work that must keep the wait time tightly bounded, it is more reliable to confirm the actual elapsed time with Bun.nanoseconds().
Difference from setTimeout
The official guide says Bun.sleep() is the same as wrapping setTimeout in a Promise. I waited 20 ms twenty times for each and compared: the medians were 20.208 ms and 20.164 ms, almost identical. The sleep I imported with import { sleep } from "bun" was the same function as Bun.sleep (sleep === Bun.sleep was true).
Waiting until a specific time
As the official documentation describes, Bun.sleep() also accepts a Date in place of a number. It waits until that time.
// date.ts
const target = new Date(Date.now() + 500);
const s = Bun.nanoseconds();
await Bun.sleep(target);
console.log(`Date まで待った時間: ${((Bun.nanoseconds() - s) / 1e6).toFixed(3)} ms`);
console.log(`目標との差: ${Date.now() - target.getTime()} ms`);
const s2 = Bun.nanoseconds();
await Bun.sleep(new Date(Date.now() - 1000));
console.log(`過去の Date: ${((Bun.nanoseconds() - s2) / 1e6).toFixed(3)} ms`);
$ bun date.ts
Date まで待った時間: 500.291 ms
目標との差: 1 ms
過去の Date: 0.021 ms
Passing a time 500 ms ahead waited 500.291 ms. Passing a time that had already passed returned immediately without waiting.
I also tried values that are not numbers, and fractional values.
| Value passed | Result |
|---|---|
-100 |
Returned after 0.037 ms (no error) |
1.5 |
Returned after 1.244 ms |
NaN |
Returned after 0.010 ms (no error) |
"100" (string) |
TypeError: sleep expects a number (milliseconds) |
Passing a negative value or NaN does not raise an error; it returns immediately. A wrong wait time from a calculation is easy to miss, so it is worth checking the value before passing it to Bun.sleep(). With 1.5, it returned after 1.244 ms, which is shorter than 1.5 ms.
Retrying with increasing delays after a failure
As an example of using Bun.sleep(), I wrote a retry after failure. In the following example, a function that fails twice and then succeeds is called again with waits that double each time: 100 ms, then 200 ms.
// retry.ts
const t0 = Bun.nanoseconds();
const ms = () => ((Bun.nanoseconds() - t0) / 1e6).toFixed(0).padStart(4);
let calls = 0;
async function unstable(): Promise<string> {
calls++;
if (calls < 3) throw new Error(`${calls}回目は失敗`);
return "成功";
}
async function withRetry<T>(fn: () => Promise<T>, retries = 3, baseMs = 100): Promise<T> {
for (let i = 0; ; i++) {
try {
return await fn();
} catch (e) {
if (i >= retries) throw e;
const wait = baseMs * 2 ** i;
console.log(`${ms()} ms: ${(e as Error).message}。${wait}ms 待って再試行`);
await Bun.sleep(wait);
}
}
}
const result = await withRetry(unstable);
console.log(`${ms()} ms: ${result}`);
$ bun retry.ts
0 ms: 1回目は失敗。100ms 待って再試行
101 ms: 2回目は失敗。200ms 待って再試行
301 ms: 成功
The second call came 101 ms after the first failure, and the third call came 200 ms later, at 301 ms, and succeeded.
Bun.sleepSync() blocks the whole thread
Bun.sleepSync(ms) is the synchronous version of Bun.sleep() (official documentation). It does not return a Promise; it stops the thread on the spot. To see the difference, I registered a setTimeout for 10 ms first, then waited 200 ms with each function.
// async.ts (sync.ts is the same, with await Bun.sleep(200) changed to Bun.sleepSync(200))
const t0 = Bun.nanoseconds();
const ms = () => ((Bun.nanoseconds() - t0) / 1e6).toFixed(1);
setTimeout(() => console.log(`${ms()} ms: setTimeout(…, 10) が動いた`), 10);
console.log(`${ms()} ms: await Bun.sleep(200) を開始`);
await Bun.sleep(200);
console.log(`${ms()} ms: await Bun.sleep(200) が終わった`);
$ bun async.ts
0.1 ms: await Bun.sleep(200) を開始
10.3 ms: setTimeout(…, 10) が動いた
200.5 ms: await Bun.sleep(200) が終わった
$ bun sync.ts
0.2 ms: Bun.sleepSync(200) を開始
200.5 ms: Bun.sleepSync(200) が終わった
201.9 ms: setTimeout(…, 10) が動いた

During await Bun.sleep(200), the timer ran at 10.3 ms. With Bun.sleepSync(200), nothing ran until the 200 ms wait finished, and the timer was delayed until 201.9 ms.
Because Bun.sleepSync() cannot let timers or other callbacks run while it waits, it suits short scripts with nothing else to run. The wait itself was about as accurate as Bun.sleep(): 1.246 ms for a 1 ms request, 100.179 ms for 100 ms, and 500.179 ms for 500 ms.





