Reputation: 5
How i can do realtime
output, without delays (including so much syscalls (assembler instruction of CPU). Trouble consists of simple call println or print.
By the way, C++ really can do realtime
output without additional functions.
By realtime
, I mean that without any delays, the program should be output or the operation should be performed. We should not expect that the program will be fully completed. For example, I ask for println
, but it is executed only when the program completes its work, let's say after println
the program is running, but the output is not carried out and you need to wait for the program to complete and only after that everything is printed.
When i run Rust program, in the begin should be welcome output or in the other stage of processing program. But when Rust program finish execute then output all content including println.
Example:
use std::io::*;
fn main() {
println!("Welcome, user!");
println!("Wait, we processing...");
/*
heavy process, example:
handler image, text, video or parse content file, tcp server
*/
}
I don't use in other processes or multithreading that I'll encounter in the future yet.
I trying famous method from Stackoverflow:
io::stdout::flush().unwrap();
I not know what makes unwrap()
method. But i can thinking what flush()
method execute flush
(clear) cache.
Example full code with Stackoverflow answers:
use std::io::*;
fn main() {
println!("Welcome, user!");
io::stdout::flush().unwrap();
println!("Wait, we processing...");
io::stdout::flush().unwrap();
/*
heavy process, example:
handler image, text, video or parse content file, tcp server
*/
}
I thinking what's this code not comfortable writen because we need write flush()
with unwrap()
methods after println or print. This situate i can make special fn for avoid DRY (Do not repeating yourself).
use std::io::*;
fn fastout(_str: &str) {
println!(_str);
io::stdout::flush().unwrap();
}
fn main() {
fastout("Welcome, user!");
fastout("Wait, we processing...");
/*
heavy process, example:
handler image, text, video or parse content file, tcp server
*/
}
I've noticed that if I run this on Linux, including WSL2, the Rust program runs faster than on Windows, according to expectations.
But, will the text be immediately displayed if I run it on Linux, I need to test this.
I not has macOS for test Rust programs. xd
Upvotes: -3
Views: 76