blob: 2b6af54598febc3c21253a58fe33a35d292a7efd (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
|
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
export const formatMemoryUsage = (bytes: number): string => {
const gb = bytes / (1024 * 1024 * 1024);
if (bytes < 1024 * 1024) {
return `${(bytes / 1024).toFixed(1)} KB`;
}
if (bytes < 1024 * 1024 * 1024) {
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}
return `${gb.toFixed(2)} GB`;
};
/**
* Formats a duration in milliseconds into a concise, human-readable string (e.g., "1h 5s").
* It omits any time units that are zero.
* @param milliseconds The duration in milliseconds.
* @returns A formatted string representing the duration.
*/
export const formatDuration = (milliseconds: number): string => {
if (milliseconds <= 0) {
return '0s';
}
if (milliseconds < 1000) {
return `${Math.round(milliseconds)}ms`;
}
const totalSeconds = milliseconds / 1000;
if (totalSeconds < 60) {
return `${totalSeconds.toFixed(1)}s`;
}
const hours = Math.floor(totalSeconds / 3600);
const minutes = Math.floor((totalSeconds % 3600) / 60);
const seconds = Math.floor(totalSeconds % 60);
const parts: string[] = [];
if (hours > 0) {
parts.push(`${hours}h`);
}
if (minutes > 0) {
parts.push(`${minutes}m`);
}
if (seconds > 0) {
parts.push(`${seconds}s`);
}
// If all parts are zero (e.g., exactly 1 hour), return the largest unit.
if (parts.length === 0) {
if (hours > 0) return `${hours}h`;
if (minutes > 0) return `${minutes}m`;
return `${seconds}s`;
}
return parts.join(' ');
};
|