记录一下通过 C 语言和 C++ 实现在终端中展示进度条的动画效果,代码同时支持 Linux 和 Windows。

C 语言实现

头文件如下

pbar.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#ifndef PBAR_H
#define PBAR_H
#ifdef __cplusplus
extern "C" {
#endif

struct pbar *pbar_create();

struct pbar *pbar_create_colorful();

struct pbar *pbar_create_simple();

struct pbar *pbar_create_simple_colorful();

void pbar_update(struct pbar *pb, double pct);

double pbar_time_cost(struct pbar *pb);

#ifdef __cplusplus
}
#endif
#endif // PBAR_H

这里导出的接口同时支持 C 和 Cpp。

具体实现的源文件如下

pbar.c
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
#include "pbar.h"

#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#ifdef _WIN32
#include <windows.h>
static LARGE_INTEGER freq; // time frequency
#else
#include <time.h>
#include <unistd.h>
#endif

#define PBAR_STYLE_BASE 0
#define PBAR_STYLE_BASE_COLORFUL 1
#define PBAR_STYLE_SIMPLE 2
#define PBAR_STYLE_SIMPLE_COLORFUL 3

struct pbar_tp {
#ifdef _WIN32
long long counter;
#else
struct timespec ts;
#endif
};

static void pbar_get_time(struct pbar_tp *tp) {
#ifdef _WIN32
LARGE_INTEGER now;
QueryPerformanceCounter(&now);
tp->counter = now.QuadPart;
#else
clock_gettime(CLOCK_MONOTONIC, &(tp->ts));
#endif
}

static double pbar_time_diff(struct pbar_tp *tp_start, struct pbar_tp *tp_end) {
#ifdef _WIN32
return (double)(tp_end->counter - tp_start->counter)
/ (double)freq.QuadPart; // seconds
#else
return (double)(tp_end->ts.tv_sec - tp_start->ts.tv_sec)
+ (double)(tp_end->ts.tv_nsec - tp_start->ts.tv_nsec)
/ 1e9; // seconds
#endif
}

static void pbar_time_str(double dt, char *time_buffer,
size_t time_buffer_len) {
if (!time_buffer || time_buffer_len == 0) { return; }

if (dt < 3600) { // mm:ss
int minutes = (int)(dt / 60);
int seconds = (int)(dt) % 60;
snprintf(time_buffer, time_buffer_len, "%02d:%02d", minutes, seconds);
}
else if (dt < 86400) { // hh:mm:ss
int hours = (int)(dt / 3600);
int minutes = ((int)(dt) % 3600) / 60;
int seconds = (int)(dt) % 60;
snprintf(time_buffer, time_buffer_len, "%02d:%02d:%02d", hours, minutes,
seconds);
}
else { // >xxh
int hours = (int)(dt / 3600);
snprintf(time_buffer, time_buffer_len, ">%dh", hours);
}
}

struct pbar {
int style;
int initialized;
double last_pct;
double last_rate;
struct pbar_tp start_time;
struct pbar_tp last_time;
};

static struct pbar *pbar_create_detail(int style) {
#ifdef _WIN32
QueryPerformanceFrequency(&freq);
#endif

struct pbar *pb = (struct pbar *)malloc(sizeof(struct pbar));
memset(pb, 0, sizeof(struct pbar));

pbar_get_time(&pb->start_time);
pb->last_time = pb->start_time;
pb->style = style;
return pb;
}

struct pbar *pbar_create() { return pbar_create_detail(PBAR_STYLE_BASE); }

struct pbar *pbar_create_colorful() {
return pbar_create_detail(PBAR_STYLE_BASE_COLORFUL);
}

struct pbar *pbar_create_simple() {
return pbar_create_detail(PBAR_STYLE_SIMPLE);
}

struct pbar *pbar_create_simple_colorful() {
return pbar_create_detail(PBAR_STYLE_SIMPLE_COLORFUL);
}

double pbar_time_cost(struct pbar *pb) {
if (pb == NULL) { return 0; }

return pbar_time_diff(&pb->start_time, &pb->last_time);
}

void pbar_update(struct pbar *pb, double pct) {
if (pb == NULL || pct < pb->last_pct) { return; }

struct pbar_tp time_now;
pbar_get_time(&time_now);
double elapsed_time = pbar_time_diff(&pb->last_time, &time_now);

double cur_rate = (pct - pb->last_pct) / elapsed_time;
if (!pb->initialized || isnan(pb->last_rate) || isinf(pb->last_rate)) {
pb->last_rate = cur_rate;
pb->initialized = 1;
}
else {
const double alpha = 0.4;
pb->last_rate = alpha * cur_rate + (1 - alpha) * pb->last_rate;
}

pb->last_time = time_now;
pb->last_pct = pct;

char color_label_buf[20] = {0};
if (pct < 0.5) {
snprintf(color_label_buf, 20, "\033[38;2;%d;%d;%dm", 255,
(int)(255 * (pct / 0.5)), 0);
}
else {
snprintf(color_label_buf, 20, "\033[38;2;%d;%d;%dm",
(int)(255 * (1 - (pct - 0.5) / 0.5)), 255, 0);
}

double cost_time = pbar_time_cost(pb);
char cost_time_buf[20] = {0};
pbar_time_str(cost_time, cost_time_buf, 20);

double eta_time = (1.0 - pct) / pb->last_rate;
char eta_time_buf[20] = {0};
pbar_time_str(eta_time, eta_time_buf, 20);

char bar_buf[21] = {0};
int filled_num = (int)(pct * 20);
for (int i = 0; i < 20; ++i) { bar_buf[i] = (i < filled_num) ? '#' : ' '; }
bar_buf[20] = '\0';

switch (pb->style) {
case PBAR_STYLE_SIMPLE: printf("\r %6.2f%%", pct * 100); break;

case PBAR_STYLE_SIMPLE_COLORFUL:
printf("\r %s%6.2f%%\033[0m", color_label_buf, pct * 100);
break;

case PBAR_STYLE_BASE_COLORFUL:
printf("\r \033[91m%6.2f%%\033[0m %s|%s|\033[0m \033[93m[%s<%s]\033[0m",
pct * 100, color_label_buf, bar_buf, cost_time_buf,
eta_time_buf);
break;

default:
case PBAR_STYLE_BASE:
printf("\r %6.2f%% |%s| [%s<%s]", pct * 100, bar_buf, cost_time_buf,
eta_time_buf);
break;
}

fflush(stdout);
}

这里提供了四种进度条样式:

  • (默认)数字百分比 + 进度条
  • 数字百分比 + 彩色进度条
  • 数字百分比
  • 彩色数字百分比

其中的色彩会随着进度逐渐变化。考虑到代码的规模,没有提供自定义样式的接口。

几种进度条的具体效果如下

测试文件如下

test.c
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
64
65
66
67
68
#include "pbar.h"

#include <stdio.h>
#include <stdlib.h>

#ifdef _WIN32
#include <windows.h>
#else
#include <time.h>
#include <unistd.h>
#endif

void common_sleep(int ms) {
if (ms <= 0) { return; }

#ifdef _WIN32
Sleep((DWORD)ms);
#else
struct timespec ts;
ts.tv_sec = ms / 1000;
ts.tv_nsec = (ms % 1000) * 1000000L;
nanosleep(&ts, NULL);
#endif
}

int main(void) {
{
struct pbar *demo1 = pbar_create_simple();
for (int i = 1; i <= 100; i++) {
pbar_update(demo1, i / 100.0);
common_sleep(i / 5);
}
printf("\ntime_cost: %.2f\n", pbar_time_cost(demo1));
free(demo1);
}

{
struct pbar *demo1 = pbar_create_simple_colorful();
for (int i = 1; i <= 100; i++) {
pbar_update(demo1, i / 100.0);
common_sleep(i / 5);
}
printf("\ntime_cost: %.2f\n", pbar_time_cost(demo1));
free(demo1);
}

{
struct pbar *demo1 = pbar_create();
for (int i = 1; i <= 100; i++) {
pbar_update(demo1, i / 100.0);
common_sleep(i);
}
printf("\ntime_cost: %.2f\n", pbar_time_cost(demo1));
free(demo1);
}

{
struct pbar *demo1 = pbar_create_colorful();
for (int i = 1; i <= 100; i++) {
pbar_update(demo1, i / 100.0);
common_sleep(i);
}
printf("\ntime_cost: %.2f\n", pbar_time_cost(demo1));
free(demo1);
}

return 0;
}

C++ 实现

使用 C++ 的实现可以用 header-only 的方式,而且支持更丰富的自定义样式,为了让写法更加简洁,使用了 C++20 的 std::format

头文件如下

progress_bar.hpp
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
#pragma once

#include <algorithm>
#include <chrono>
#include <cmath>
#include <format>
#include <iostream>
#include <string>
#include <utility>
#include <vector>

class ColorGradient {
public:
struct RGB {
int r;
int g;
int b;
};

ColorGradient() = default;

explicit ColorGradient(std::vector<RGB> colors)
: m_colors(std::move(colors)) {}

explicit ColorGradient(RGB color) : ColorGradient(std::vector{color}) {}

std::string prefix(double pct) const {
pct = std::clamp(pct, 0.0, 1.0);

if (m_colors.empty()) { return ""; }

if (m_colors.size() == 1) { return rgb_to_ansi(m_colors[0]); }

double seg = 1.0 / static_cast<double>(m_colors.size() - 1);
size_t idx =
std::min(static_cast<size_t>(pct / seg), m_colors.size() - 2);

double local_t = (pct - static_cast<double>(idx) * seg) / seg;

RGB c1 = m_colors[idx];
RGB c2 = m_colors[idx + 1];

RGB c = interpolate(c1, c2, local_t);
return rgb_to_ansi(c);
}

static std::string suffix() { return "\033[0m"; }

std::string colorful(std::string msg, double pct) const {
return prefix(pct) + msg + suffix();
}

// red -> yellow -> green
static ColorGradient Heat() {
return ColorGradient({{255, 0, 0}, // red
{255, 255, 0}, // yellow
{0, 255, 0}} // green
);
}

// red -> purple -> blue
static ColorGradient Energy() {
return ColorGradient({
{255, 0, 0}, // red
{180, 0, 180}, // purple
{0, 128, 255} // blue
});
}

// deep blue -> cyan -> light green
static ColorGradient Ocean() {
return ColorGradient({
{0, 32, 96}, // deep blue
{0, 128, 192}, // cyan
{0, 255, 128} // light green
});
}

private:
std::vector<RGB> m_colors;

static RGB interpolate(const RGB &c1, const RGB &c2, double t) {
return {
static_cast<int>(c1.r + (c2.r - c1.r) * t),
static_cast<int>(c1.g + (c2.g - c1.g) * t),
static_cast<int>(c1.b + (c2.b - c1.b) * t),
};
}

static std::string rgb_to_ansi(const RGB &c) {
return "\033[38;2;" + std::to_string(c.r) + ";" + std::to_string(c.g)
+ ";" + std::to_string(c.b) + "m";
}
};

struct ProgressStyle {
size_t length = 20;
std::string fill = "#";
std::string empty = " ";
std::string left = "|";
std::string right = "|";
std::vector<std::string> active;

std::string prefix_desc;
std::string suffix_desc;

ColorGradient color_of_pct;
ColorGradient color_of_bar;
ColorGradient color_of_time;

static ProgressStyle Classic() {
return {.length = 20,
.fill = "#",
.empty = " ",
.left = "|",
.right = "|",
.active = std::vector<std::string>{"|", "/", "-", "\\"},
.prefix_desc = {},
.suffix_desc = {},
.color_of_pct = {},
.color_of_bar = {},
.color_of_time = {}};
}

static ProgressStyle Block() {
return {.length = 20,
.fill = "█",
.empty = " ",
.left = "▕",
.right = "▏",
.active = std::vector<std::string>{" ", "▏", "▎", "▍", "▌", "▋",
"▊", "▉"},
.prefix_desc = {},
.suffix_desc = {},
.color_of_pct = {},
.color_of_bar = {},
.color_of_time = {}};
}

static ProgressStyle Braille() {
return {.length = 20,
.fill = "⣿",
.empty = " ",
.left = "|",
.right = "|",
.active = std::vector<std::string>{" ", "⡀", "⡄", "⡆", "⡇", "⡏",
"⡟", "⡿"},
.prefix_desc = {},
.suffix_desc = {},
.color_of_pct = {},
.color_of_bar = {},
.color_of_time = {}};
}
};

class DataUpdater {
public:
DataUpdater()
: m_start(std::chrono::steady_clock::now()), m_last(m_start) {}

bool update(double pct) {
if (pct < m_last_pct) return false;

auto now = std::chrono::steady_clock::now();
double dt = static_cast<double>(
std::chrono::duration_cast<std::chrono::milliseconds>(
now - m_last)
.count())
/ 1000.0;

double cur_rate = (pct - m_last_pct) / dt;

bool bad = std::isnan(m_rate) || std::isinf(m_rate);
if (!m_rate_ok || bad) {
m_rate = cur_rate;
m_rate_ok = true;
}
else { m_rate = alpha * cur_rate + (1 - alpha) * m_rate; }

m_last = now;
m_last_pct = pct;
return true;
}

double cost() const {
auto d = std::chrono::duration_cast<std::chrono::milliseconds>(
m_last - m_start);
return static_cast<double>(d.count()) / 1000.0;
}

double left() const {
if (!m_rate_ok) return 0;
return (1.0 - m_last_pct) / m_rate;
}

double last_pct() const { return m_last_pct; }

double last_rate() const { return m_rate; }

private:
static constexpr double alpha = 0.4;

std::chrono::steady_clock::time_point m_start;
std::chrono::steady_clock::time_point m_last;

double m_last_pct = 0;
double m_rate = 0;
bool m_rate_ok = false;
};

class Progress {
public:
Progress() : Progress(ProgressStyle::Classic()) {}

explicit Progress(ProgressStyle st) : m_st(std::move(st)) {
m_lbars.reserve(m_st.length + 1);
m_lbars.emplace_back("");
m_rbars.reserve(m_st.length + 1);
m_rbars.emplace_back("");
m_rbars.emplace_back("");

std::string tmp1;
std::string tmp2;
for (size_t i = 1; i <= m_st.length; i++) {
tmp1 += m_st.fill;
tmp2 += m_st.empty;
m_lbars.push_back(tmp1);
m_rbars.push_back(tmp2);
}
}

void update(double pct) {
m_upt.update(pct);

auto msg = showline(m_upt.last_pct(), m_upt.cost(), m_upt.left(),
m_upt.last_rate());

std::cout << std::format("\r {}{}{}", m_st.prefix_desc, msg,
m_st.suffix_desc)
<< std::flush;
}

static void nextline() { std::cout << "\n"; }

private:
DataUpdater m_upt;
ProgressStyle m_st;
std::vector<std::string> m_lbars;
std::vector<std::string> m_rbars;

std::string pct_bar(double pct) {
size_t len = m_st.length;
size_t n =
std::clamp(static_cast<size_t>(pct * static_cast<double>(len)),
static_cast<size_t>(0), len);

double block_pct = 1.0 / static_cast<double>(len);
double rest_pct = pct - block_pct * static_cast<int>(n);
std::string last_str;

if (!m_st.active.empty() && n < len) {
auto idx = static_cast<size_t>(
static_cast<double>(m_st.active.size()) * rest_pct / block_pct);
last_str = m_st.active[idx];
}

return m_st.left + m_lbars[n] + last_str + m_rbars[len - n]
+ m_st.right;
}

static std::string time_str(double dt) {
if (dt < 3600) {
return std::format("{:02}:{:02}", static_cast<int>(dt / 60),
static_cast<int>(dt) % 60);
}
if (dt < 86400) {
return std::format("{:02}:{:02}:{:02}", static_cast<int>(dt / 3600),
(static_cast<int>(dt) % 3600) / 60,
static_cast<int>(dt) % 60);
}
return std::format(">{}h", static_cast<int>(dt / 3600));
}

std::string showline(double pct, double time_cost, double time_left,
double rate) {
auto bar = pct_bar(pct);

auto result = std::format(
"{}{:6.2f}%{} {}{}{} {}[{}<{}]{}", m_st.color_of_pct.prefix(pct),
pct * 100, ColorGradient::suffix(), m_st.color_of_bar.prefix(pct),
bar, ColorGradient::suffix(), m_st.color_of_time.prefix(pct),
time_str(time_cost), time_str(time_left), ColorGradient::suffix());

return result;
}
};

测试文件如下

test.cpp
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
#include "progress_bar.hpp"

#include <thread>

#ifdef _WIN32
#include "windows.h" // IWYU pragma: keep
#endif

void test_pbar(Progress pbar) {
for (int i = 1; i <= 100; i++) {
pbar.update(i / 100.0);
std::this_thread::sleep_for(std::chrono::milliseconds(i / 2));
}
Progress::nextline();
}

int main() {
#ifdef _WIN32
SetConsoleOutputCP(65001);
SetConsoleCP(65001);
#endif

{ test_pbar(Progress{}); }
{
auto st = ProgressStyle::Classic();
st.color_of_pct = ColorGradient{{0, 0, 255}};
st.color_of_bar = ColorGradient::Ocean();
st.color_of_time = ColorGradient::Energy();
test_pbar(Progress{st});
}
{
auto st = ProgressStyle::Block();
st.color_of_pct = ColorGradient{{0, 255, 0}};
st.color_of_bar = ColorGradient::Energy();
test_pbar(Progress{st});
}
{
auto st = ProgressStyle::Braille();
st.color_of_pct = ColorGradient{{0, 255, 0}};
st.color_of_bar = ColorGradient::Heat();
test_pbar(Progress{st});
}
return 0;
}

运行效果如下