用C++实现一个命令行进度条的示例代码

缘起

最近做遥感影像融合的GWPCA方法,在带宽比较大的时候速度太慢了,需要有个进度条指示一下,然后我去找进度条的库,发现github上面的C/C++的相应的库似乎没有能在VS下跑的,自己花了点时间写了一个。

效果

实现

大概需要考虑这样几个要素

  • 已完成的百分比
  • 执行速度
  • 已执行的时间
  • 剩余时间

另外进度条的引入不能破坏已有的执行结构,最好和Python的tqdm库类似,通过 start , update 等函数来完成整个进度条,因此对于C语言来说,需要一个定时器,定期将进度条进行重绘(不可能更新一次就重绘一次),因此整个进度条就包含了两个类,一个是进度条类,一个是定时器类。另外需要考虑线程安全的问题。

// Progress.hpp
#pragma once

#include <ctime>
#include <chrono>
#include <iostream>
#include <iomanip>
#include "Timer.hpp"

using namespace std::chrono;

class ProgressBar
{
protected:
  // 进度条的长度(不包含前后缀)
	unsigned int ncols;
  // 已完成的数量
	std::atomic<unsigned int> finishedNum;
  // 上次的已完成数量
	unsigned int lastNum;
  // 总数
	unsigned int totalNum;
  // 进度条长度与百分比之间的系数
	double colsRatio;
  // 开始时间
	steady_clock::time_point beginTime;
  // 上次重绘的时间
	steady_clock::time_point lastTime;
  // 重绘周期
	milliseconds interval;
	Timer timer;
public:
	ProgressBar(unsigned int totalNum, milliseconds interval) : totalNum(totalNum), interval(interval), finishedNum(0), lastNum(0), ncols(80), colsRatio(0.8) {}
  // 开始
	void start();
  // 完成
	void finish();
  // 更新
	void update() { return this->update(1); }
  // 一次更新多个数量
	void update(unsigned int num) { this->finishedNum += num; }
  // 获取进度条长度
	unsigned int getCols() { return this->ncols; }
  // 设置进度条长度
	void setCols(unsigned int ncols) { this->ncols = ncols; this->colsRatio = ncols / 100; }
  // 重绘
	void show();
};
void ProgressBar::start() {
  // 记录开始时间,并初始化定时器
	this->beginTime = steady_clock::now();
	this->lastTime = this->beginTime;
	// 定时器用于定时调用重绘函数
	this->timer.start(this->interval.count(), std::bind(&ProgressBar::show, this));
}

// 重绘函数
void ProgressBar::show() {
  // 清除上次的绘制内容
	std::cout << "\r";
  // 记录重绘的时间点
	steady_clock::time_point now = steady_clock::now();
	// 获取已完成的数量
	unsigned int tmpFinished = this->finishedNum.load();
	// 获取与开始时间和上次重绘时间的时间间隔
	auto timeFromStart = now - this->beginTime;
	auto timeFromLast = now - this->lastTime;
	// 这次完成的数量
	unsigned int gap = tmpFinished - this->lastNum;
	// 计算速度
	double rate = gap / duration<double>(timeFromLast).count();
	// 应显示的百分数
	double present = (100.0 * tmpFinished) / this->totalNum;
	// 打印百分数
	std::cout << std::setprecision(1) << std::fixed << present << "%|";
	// 计算应该绘制多少=符号
	int barWidth = present * this->colsRatio;
	// 打印已完成和未完成进度条
	std::cout << std::setw(barWidth) << std::setfill('=') << "=";
	std::cout << std::setw(this->ncols - barWidth) << std::setfill(' ') << "|";

	// 打印速度
	std::cout << std::setprecision(1) << std::fixed << rate << "op/s|";
	// 之后的两部分内容分别为打印已过的时间和剩余时间
	int timeFromStartCount = duration<double>(timeFromStart).count();

	std::time_t tfs = timeFromStartCount;
	tm tmfs;
	gmtime_s(&tmfs, &tfs);
	std::cout << std::put_time(&tmfs, "%X") << "|";

	int timeLast;
	if (rate != 0) {
    // 剩余时间的估计是用这次的速度和未完成的数量进行估计
		timeLast = (this->totalNum - tmpFinished) / rate;
	}
	else {
		timeLast = INT_MAX;
	}

	if ((this->totalNum - tmpFinished) == 0) {
		timeLast = 0;
	}

	std::time_t tl = timeLast;
	tm tml;
	gmtime_s(&tml, &tl);
	std::cout << std::put_time(&tml, "%X");

	this->lastNum = tmpFinished;
	this->lastTime = now;
}

void ProgressBar::finish() {
  // 停止定时器
	this->timer.stop();
	std::cout << std::endl;
}
// Timer.hpp
#pragma once
#include <functional>
#include <chrono>
#include <thread>
#include <atomic>
#include <memory>
#include <mutex>
#include <condition_variable>

using namespace std::chrono;

class Timer
{
public:
	Timer() : _expired(true), _try_to_expire(false)
	{}

	Timer(const Timer& timer)
	{
		_expired = timer._expired.load();
		_try_to_expire = timer._try_to_expire.load();
	}

	~Timer()
	{
		stop();
	}

	void start(int interval, std::function<void()> task)
	{
		// is started, do not start again
		if (_expired == false)
			return;

		// start async timer, launch thread and wait in that thread
		_expired = false;
		std::thread([this, interval, task]() {
			while (!_try_to_expire)
			{
				// sleep every interval and do the task again and again until times up
				std::this_thread::sleep_for(std::chrono::milliseconds(interval));
				task();
			}

			{
				// timer be stopped, update the condition variable expired and wake main thread
				std::lock_guard<std::mutex> locker(_mutex);
				_expired = true;
				_expired_cond.notify_one();
			}
		}).detach();
	}

	void startOnce(int delay, std::function<void()> task)
	{
		std::thread([delay, task]() {
			std::this_thread::sleep_for(std::chrono::milliseconds(delay));
			task();
		}).detach();
	}

	void stop()
	{
		// do not stop again
		if (_expired)
			return;

		if (_try_to_expire)
			return;

		// wait until timer
		_try_to_expire = true; // change this bool value to make timer while loop stop
		{
			std::unique_lock<std::mutex> locker(_mutex);
			_expired_cond.wait(locker, [this] {return _expired == true; });

			// reset the timer
			if (_expired == true)
				_try_to_expire = false;
		}
	}

private:
	std::atomic<bool> _expired; // timer stopped status
	std::atomic<bool> _try_to_expire; // timer is in stop process
	std::mutex _mutex;
	std::condition_variable _expired_cond;
};

定时器类是直接copy了一篇 文章

可以增加的功能

读者可以自行调整一下结构,增加一些有意思的小功能,比如说用于表示完成内容的符号可以替换成大家喜欢的符号,或者加个颜色什么的

还有一些复杂的功能,比如说分组进度条等,不过这个由于我没这方面的需求,因此就没研究了,读者可以自行研究

到此这篇关于用C++实现一个命令行进度条的示例代码的文章就介绍到这了,更多相关C++ 命令行进度条内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • C++命令行解析包gflags的使用教程

    前言 gflags 是 Google 提供的一个命令行参数处理的开源库,目前已经独立开源,比传统的 getopt() 功能更加强大,可以将不同的参数定义分布到各个源码文件中,不需要集中管理. 提供了 C++ 和 Python 两个版本,这里仅详细介绍 C++ 版本的使用方式. 简介 配置参数分开还是集中管理没有严格的约束,关键要看项目里的统一规范,只是,gflags 可以支持这两种方式,允许用户更加灵活的使用. 当将参数分布到各个源码文件中时,如果定义了相同的参数,那么在编译的时候会直接报错.

  • C++实现希尔排序(ShellSort)

    本文实例为大家分享了C++实现希尔排序的具体代码,供大家参考,具体内容如下 一.思路: 希尔排序:又称缩小增量排序,是一种改进的插入排序算法,是不稳定的. 设排序元素序列有n个元素,首先取一个整数gap<n作为间隔,将全部元素分为gap个子序列,所有距离为gap的元素放在同一个子序列中,在每一个子序列中分别施行直接插入排序.然后缩小间隔gap,重复上述的子序列和排序工作. 二.实现程序: #include <iostream> using namespace std; const int

  • C++执行shell命令的多种实现方法

    目录 1.system(执行shell 命令) 2.popen(建立管道I/O) 3.使用vfork()新建子进程,然后调用exec函数族 在linux系统下,用C++程序执行shell命令有多种方式 1.system(执行shell 命令) 相关函数:fork,execve,waitpid,popen 表头文件:#include<stdlib.h> 函数原型:int system(const char * string); 函数说明 :system()会调用fork()产生子进程,由子进程来

  • C++实现模拟shell命令行(代码解析)

    目录 一.解析 二.执行命令函数 三.模拟shell 四.完整代码 四.运行结果 一.解析 /** * 进行命令行解析: * 多个空格 * 分割符:< > | * */ void parse(){ std::string line; getline(std::cin, line); /** 解析字符串 */ int len = line.size(), i=0; std::string tmp; std::vector<std::string> tmp_vc; while(i &l

  • 用C++实现一个命令行进度条的示例代码

    缘起 最近做遥感影像融合的GWPCA方法,在带宽比较大的时候速度太慢了,需要有个进度条指示一下,然后我去找进度条的库,发现github上面的C/C++的相应的库似乎没有能在VS下跑的,自己花了点时间写了一个. 效果 实现 大概需要考虑这样几个要素 已完成的百分比 执行速度 已执行的时间 剩余时间 另外进度条的引入不能破坏已有的执行结构,最好和Python的tqdm库类似,通过 start , update 等函数来完成整个进度条,因此对于C语言来说,需要一个定时器,定期将进度条进行重绘(不可能更

  • Python调用命令行进度条的方法

    本文实例讲述了Python调用命令行进度条的方法.分享给大家供大家参考.具体分析如下: 关键点是输出'\r'这个字符可以使光标回到一行的开头,这时输出其它内容就会将原内容覆盖. import time import sys def progress_test(): bar_length=20 for percent in xrange(0, 100): hashes = '#' * int(percent/100.0 * bar_length) spaces = ' ' * (bar_lengt

  • SpringBoot如何实现一个实时更新的进度条的示例代码

    前言 博主近期接到一个任务,大概内容是:导入excel表格批量修改状态,期间如果发生错误则所有数据不成功,为了防止重复提交,做一个类似进度条的东东. 那么下面我会结合实际业务对这个功能进行分析和记录. 正文 思路 前端使用bootstrap,后端使用SpringBoot分布式到注册中心,原先的想法是导入表格后异步调用修改数据状态的方法,然后每次计算修改的进度然后存放在session中,前台jquery写定时任务访问获取session中的进度,更新进度条进度和百分比.但是这存在session在服务

  • python tqdm实现进度条的示例代码

    一.前言 \quad \quad 有时候在使用Python处理比较耗时操作的时候,为了便于观察处理进度,这时候就需要通过进度条将处理情况进行可视化展示,以便我们能够及时了解情况.这对于第三方库非常丰富的Python来说,想要实现这一功能并不是什么难事. \quad \quad tqdm就能非常完美的支持和解决这些问题,可以实时输出处理进度而且占用的CPU资源非常少,支持循环处理.多进程.递归处理.还可以结合linux的命令来查看处理情况,等进度展示. 我们先来看一下进度条的效果. from tq

  • 使用Apache commons-cli包进行命令行参数解析的示例代码

    Apache的commons-cli包是专门用于解析命令行参数格式的包. 依赖: <dependency> <groupId>commons-cli</groupId> <artifactId>commons-cli</artifactId> <version>1.3.1</version> </dependency> 使用此包需要: 1.先定义有哪些参数需要解析.哪些参数有额外的选项.每个参数的描述等等,对应

  • 小程序视频或音频自定义可拖拽进度条的示例代码

    小程序原生组件的音频播放时并没有进度条的显示,而此次项目中,鉴于原生的视频进度条样式太丑,产品要求做一个可拖拽的进度条满足需求. 视频和音频提供的api大致是相似的,可以根据以下代码修改为与音频相关的进度条. wxml的结构如下: <video id="myVideo" src="http://wxsnsdy.tc.qq.com/105/20210/snsdyvideodownload?filekey=30280201010421301f0201690402534804

  • Unity命令行打包WebGL的示例代码

    1.扫描所有场景,保存并添加到Build Settings中 using System.Collections; using System.Collections.Generic; using System.IO; using UnityEditor; using UnityEngine; using UnityEngine.SceneManagement; public class SceneUtils { #if UNITY_EDITOR public static void Refresh

  • 利用ffmpeg命令行转压视频示例代码

    在开始本文的正文之前,首先得安装好ffmpeg程序(Linux下还得安装x264编码).Mac下直接用brew安装: brew install ffmpeg --with-faac --with-fdk-aac --with-ffplay --with-fontconfig --with-freetype --with-libass --with-libbluray --with-libcaca --with-libsoxr --with-libquvi --with-frei0r --with

  • iOS中利用CoreAnimation实现一个时间的进度条效果

    在iOS中实现进度条通常都是通过不停的设置progress来完成的,这样的进度条适用于网络加载(上传下载文件.图片等).但是对于录制视频这样的需求的话,如果是按照每秒来设置进度的话,显得有点麻烦,于是我就想直接用CoreAnimation来按时间做动画,只要设置最大时间,其他的就不用管了,然后在视频暂停与继续录制时,对动画进行暂停和恢复即可.录制视频的效果如下: 你可以在这里下载demo 那么接下来就是如何用CoreAnimation实现一个进度条控件了. 首先呢,让我们创建一个继承自CASha

  • 如何使用Swift来实现一个命令行工具的方法

    本文即简单介绍了如何在Swift中开发命令行工具,以及与Shell命令的交互.水文一篇,不喜勿喷. 主要是使用该工具来解析微信的性能监控组件Matrix的OOM Log. 基本模块 这里,仅简单介绍了常见的基本模块. Process Process类可以用来打开另外一个子进程,并监控其运行情况. launchPath:指定了执行路径.如可以设置为 /usr/bin/env ,这个命令可以用于打印本机上所有的环境变量:也可以用于执行shell命令,如果你接了参数的话.本文的Demo就用它来执行输入

随机推荐