Here's a situation. I'm allocating memory using the following function
let addr = windows::Win32::System::Memory::VirtualAlloc(
ptr::null_mut(),
size,
windows::Win32::System::Memory::MEM_RESERVE | windows::Win32::System::Memory::MEM_COMMIT,
windows::Win32::System::Memory::PAGE_READWRITE,
);
Upon successful allocation, the resulting memory is cast to *mut u8 and everyone's happy until it's a time to deallocate this same space. Here's how I approach it
let result = System::Memory::VirtualFree(
ptr as *mut c_void,
size,
windows::Win32::System::Memory::MEM_DECOMMIT).0;
In Win32 API docs stated that upon successful reclamation of memory VirtualFree spits out a non-zero value, but in my case the return value turns out to be a zero. I was quite dismayed at first, so I decided to get right into the weeds to further investigate the problem. During my investigation I found out that calling GetLastError would give me a more detailed explanation of what I might have done wrong. The value this function ended up returning was 0x57, i.e ERROR_INVALID_PARAMETER. As that issue has been a primary source of majority of negative emotions for quite a while, I've had a lot of time to experiment with input values to these precious functions. And here's a thing. The setting I started describing the problem with functions perfectly when I'm running tests in release mode, but is completely off the table when it comes to debug mode. When I pass 0 as a second argument to VirtualFree, and MEM_RELEASE as a third one, it ends up crashing in both modes. So, how do I escape this nightmare and finally resolve the issue?
UPD
I apologize for the lack of context. So, the problem occurs when I'm running the following test
#[test]
fn stress() {
let mut rng = rand::thread_rng();
let seed: u64 = rng.gen();
let seed = seed % 10000;
run_stress(seed);
}
fn run_stress(seed: u64) {
let mut a = Dlmalloc::new();
println!("++++++++++++++++++++++ seed = {}\n", seed);
let mut rng = StdRng::seed_from_u64(seed);
let mut ptrs = Vec::new();
let max = if cfg!(test_lots) { 1_000_000 } else { 10_000 };
unsafe {
for _k in 0..max {
let free = !ptrs.is_empty()
&& ((ptrs.len() < 10_000 && rng.gen_bool(1f64 / 3f64)) || rng.gen());
if free {
let idx = rng.gen_range(0, ptrs.len());
let (ptr, size, align) = ptrs.swap_remove(idx);
println!("ptr: {:p}, size = {}", ptr, size);
a.free(ptr, size, align); // crashes right after the call to this function
continue;
}
if !ptrs.is_empty() && rng.gen_bool(1f64 / 100f64) {
let idx = rng.gen_range(0, ptrs.len());
let (ptr, size, align) = ptrs.swap_remove(idx);
let new_size = if rng.gen() {
rng.gen_range(size, size * 2)
} else if size > 10 {
rng.gen_range(size / 2, size)
} else {
continue;
};
let mut tmp = Vec::new();
for i in 0..cmp::min(size, new_size) {
tmp.push(*ptr.add(i));
}
let ptr = a.realloc(ptr, size, align, new_size);
assert!(!ptr.is_null());
for (i, byte) in tmp.iter().enumerate() {
assert_eq!(*byte, *ptr.add(i));
}
ptrs.push((ptr, new_size, align));
}
let size = if rng.gen() {
rng.gen_range(1, 128)
} else {
rng.gen_range(1, 128 * 1024)
};
let align = if rng.gen_bool(1f64 / 10f64) {
1 << rng.gen_range(3, 8)
} else {
8
};
let zero = rng.gen_bool(1f64 / 50f64);
let ptr = if zero {
a.calloc(size, align)
} else {
a.malloc(size, align)
};
for i in 0..size {
if zero {
assert_eq!(*ptr.add(i), 0);
}
*ptr.add(i) = 0xce;
}
ptrs.push((ptr, size, align));
}
}
}
I should point out that it doesn't crash on a particular iteration -- this number always changes.
This is the excerpt from the dlmalloc-rust crate.
The crate I'm using for interacting with winapi is windows-rs
Here's an implementation of free
pub unsafe fn free(ptr: *mut u8, size: usize) -> bool {
let result = System::Memory::VirtualFree(
ptr as *mut c_void,
0,
windows::Win32::System::Memory::MEM_RELEASE).0;
if result == 0 {
let cause = windows::Win32::Foundation::GetLastError().0;
dlverbose!("{}", cause);
}
result != 0
}
Related
I have finished converting an application that I made in JavaScript to Rust for increased performance. I am learning to program, and all the application does is work out the multiplicative persistence of any number in a range. It multiplies all digits together to form a new number, then repeats until the number becomes less than 10.
My issue is, my program written in JavaScript is over 5 times faster than the same in Rust. I must be doing something wrong with converting Strings to ints somewhere, I even tried swapping i128 to i64 and it made little difference.
If I run "cargo run --release" it is still slower!
Please can somebody look through my code to work out if there is any part of it that is causing the issues? Thank you in advance :)
fn multiplicative_persistence(mut user_input: i128) -> i128 {
let mut steps: i128 = 0;
let mut numbers: Vec<i128> = Vec::new();
while user_input > 10 {
let string_number: String = user_input.to_string();
let digits: Vec<&str> = string_number.split("").collect();
let mut sum: i128 = 1;
let digits_count = digits.len();
for number in 1..digits_count - 1 {
sum *= digits[number].parse::<i128>().unwrap();
}
numbers.push(sum);
steps += 1;
user_input = sum;
}
return steps;
}
fn main() {
// let _user_input: i128 = 277777788888899;
let mut highest_steps_count: i128 = 0;
let mut highest_steps_number: i128 = 0;
let start: i128 = 77551000000;
let finish: i128 = 1000000000000000;
for number in start..=finish {
// println!("{}: {}", number, multiplicative_persistence(number));
if multiplicative_persistence(number) > highest_steps_count {
highest_steps_count = multiplicative_persistence(number);
highest_steps_number = number;
}
if number % 1000000 == 0 {
println!("Upto {} so far: {}", number, highest_steps_number);
}
}
println!("Highest step count: {} at {}", highest_steps_number, highest_steps_count);
}
I do plan to use the numbers variable in the function but I have not learnt enough to know how to properly return it as an associative array.
Maybe the issue is that converting a number to a string, and then re-converting it again into a number is not that fast, and avoidable. You don't need this intermediate step:
fn step(mut x: i128) -> i128 {
let mut result = 1;
while x > 0 {
result *= x % 10;
x /= 10;
}
result
}
fn multiplicative_persistence(mut user_input: i128) -> i128 {
let mut steps = 0;
while user_input > 10 {
user_input = step(user_input);
steps += 1;
}
steps
}
EDIT Just out of curiosity, I'd like to know whether the bottleneck is really due to the string conversion or to the rest of the code that is somehow wasteful. Here is an example that does not call .split(""), does not re-allocate that intermediate vector, and only allocates once, not at each step, the string.
#![feature(fmt_internals)]
use std::fmt::{Formatter, Display};
fn multiplicative_persistence(user_input: i128) -> i128 {
let mut steps = 0;
let mut digits = user_input.to_string();
while user_input > 10 {
let product = digits
.chars()
.map(|x| x.to_digit(10).unwrap())
.fold(1, |acc, i| acc*i);
digits.clear();
let mut formatter = Formatter::new(&mut digits);
Display::fmt(&product, &mut formatter).unwrap();
steps += 1;
}
steps
}
I have basically inlined the string conversion that would be performed by .to_string() in order to re-use the already-allocated buffer, instead of re-allocating one each iteration. You can try it out on the playground. Note that you need a nightly compiler because it makes use of an unstable feature.
#![feature(map_first_last)]
use num_cpus;
use std::collections::BTreeMap;
use ordered_float::OrderedFloat;
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Instant;
const MONO_FREQ: [f64; 26] = [
8.55, 1.60, 3.16, 3.87, 12.1, 2.18, 2.09, 4.96, 7.33, 0.22, 0.81, 4.21, 2.53, 7.17, 7.47, 2.07,
0.10, 6.33, 6.73, 8.94, 2.68, 1.06, 1.83, 0.19, 1.72, 0.11,
];
fn main() {
let ciphertext : String = "helloworldthisisatest".to_string();
concurrent( &ciphertext);
parallel( &ciphertext);
}
fn concurrent(ciphertext : &String) {
let start = Instant::now();
for _ in 0..50000 {
let mut best_fit : f64 = chi_squared(&ciphertext);
let mut best_key : u8 = 0;
for i in 1..26 {
let test_fit = chi_squared(&decrypt(&ciphertext, i));
if test_fit < best_fit {
best_key = i;
best_fit = test_fit;
}
}
}
let elapsed = start.elapsed();
println!("Concurrent : {} ms", elapsed.as_millis());
}
fn parallel(ciphertext : &String) {
let cpus = num_cpus::get() as u8;
let start = Instant::now();
for _ in 0..50000 {
let mut best_result : f64 = chi_squared(&ciphertext);
for i in (0..26).step_by(cpus.into()) {
let results = Arc::new(Mutex::new(BTreeMap::new()));
let mut threads = vec![];
for ii in i..i+cpus {
threads.push(thread::spawn({
let clone = Arc::clone(&results);
let test = OrderedFloat(chi_squared(&decrypt(&ciphertext, ii)));
move || {
let mut v = clone.lock().unwrap();
v.insert(test, ii);
}
}));
}
for t in threads {
t.join().unwrap();
}
let lock = Arc::try_unwrap(results).expect("Lock still has multiple owners");
let hold = lock.into_inner().expect("Mutex cannot be locked");
if hold.last_key_value().unwrap().0.into_inner() > best_result {
best_result = hold.last_key_value().unwrap().0.into_inner();
}
}
}
let elapsed = start.elapsed();
println!("Parallel : {} ms", elapsed.as_millis());
}
fn decrypt(ciphertext : &String, shift : u8) -> String {
ciphertext.chars().map(|x| ((x as u8 + shift - 97) % 26 + 97) as char).collect()
}
pub fn chi_squared(text: &str) -> f64 {
let mut result: f64 = 0.0;
for (pos, i) in get_letter_counts(text).iter().enumerate() {
let expected = MONO_FREQ[pos] * text.len() as f64 / 100.0;
result += (*i as f64 - expected).powf(2.0) / expected;
}
return result;
}
fn get_letter_counts(text: &str) -> [u64; 26] {
let mut results: [u64; 26] = [0; 26];
for i in text.chars() {
results[((i as u64) - 97) as usize] += 1;
}
return results;
}
Sorry to dump so much code, but i have no idea where the problem is, no matter what i try the parallel code seems to be around 100x slower.
I think that the problem may be in the chi_squared function as i don't know if this is running in parallel.
I have tried arc mutex, rayon and messaging and all slow it down when it should speed it up. What could I do to make this faster?
Your code calculates chi_squared function on main thread here is the correct version.
for ii in i..i + cpus {
let cp = ciphertext.clone();
let clone = Arc::clone(&results);
threads.push(thread::spawn(move || {
let test = OrderedFloat(chi_squared(&decrypt(&cp, ii)));
let mut v = clone.lock().unwrap();
v.insert(test, ii);
}));
}
Note that it does not matter if it is calculated parallel or not because spawning 50000*26 threads and synchronization overhead between threads are what makes up the 100x difference in the first place. Using a threadpool implementation would reduce the overhead but the result will still be much slower than single threaded version. The only thing you can do is assigning work in the outer loop (0..50000 ) however i am guessing you are trying to parallelize inside the main loop.
I am learning Rust. I am trying to calculate a list of prime numbers up to some number. For that I need to create a vector (vec1) inside an if block and use it outside the scope of the if.
I tried a code with the same logic in MATLAB and it works.
A simplified version of the actual code looks like this:
fn main() {
let mut initiate = 1;
let mut whilechecker = 2;
while whilechecker > 0 {
whilechecker = whilechecker - 1;
if initiate == 1 {
let mut vec1 = vec![2];
}
for i in &vec1 {
if *i == 2 {
break;
}
} //for
initiate = 2;
vec1.push(5);
} //while
} //main
It is supposed to put a list of prime numbers in vec1. But since it is simplified code it should compile and giving a vector (vec1) will suffice.
But the compiler says:
cannot find value vec1 in this scope
at for i in &vec1{ and at vec1.push(5);.
Can you make it compile?
There's no reason to have the complicated if initialize==1 checking. Just move the initialization of the vector outside the while loop, so it gets done only once:
fn main() {
let mut whilechecker = 2;
let mut vec1 = vec![2];
while whilechecker > 0 {
whilechecker = whilechecker - 1;
for i in &vec1 {
if *i == 2 {
break;
}
} //for
vec1.push(5);
} //while
} //main
I don't get the thing which you actually want. But here is an example which may help you to define the global scope variable.
fn main() {
let mut initiate = 1;
let mut whilechecker = 2;
let mut vec1 = Vec::new();
while whilechecker > 0 {
if initiate == 1 {
let mut vec1 = vec![2];
}
for i in &vec1 {
if *i == 2 {
break;
}
}
initiate = 2;
vec1.push(5);
whilechecker = whilechecker - 1;
}
println!("{:?}", vec1);
}
The output of the given code is:
[5, 5]
I implemented the Miller-Rabin Strong Pseudoprime Test in Rust using BigUint to support arbitrary large primes. To run through the numbers between 5 and 10^6, it took about 40s with cargo run --release.
I implemented the same algorithm with Java's BigInteger and the same test took 10s to finish. Rust appears to be 4 times slower. I assume this is caused by the implementation of num::bigint.
Is this just the current state of num::bigint, or can anyone spot any obvious improvement in my code? (Mainly about how I used the language. Regardless whether my implementation of the algorithm is good or bad, it is almost implemented exactly the same in both languages - so does not cause the difference in performance.)
I did notice there are lots of clone() required, due to Rust's ownership model, that could well impact the speed to some level. But I guess there is no way around that, am I right?
Here is the code:
extern crate rand;
extern crate num;
extern crate core;
extern crate time;
use std::time::{Duration};
use time::{now, Tm};
use rand::Rng;
use num::{Zero, One};
use num::bigint::{RandBigInt, BigUint, ToBigUint};
use num::traits::{ToPrimitive};
use num::integer::Integer;
use core::ops::{Add, Sub, Mul, Div, Rem, Shr};
fn find_r_and_d(i: BigUint) -> (u64, BigUint) {
let mut d = i;
let mut r = 0;
loop {
if d.clone().rem(&2u64.to_biguint().unwrap()) == Zero::zero() {
d = d.shr(1usize);
r = r + 1;
} else {
break;
}
}
return (r, d);
}
fn might_be_prime(n: &BigUint) -> bool {
let nsub1 = n.sub(1u64.to_biguint().unwrap());
let two = 2u64.to_biguint().unwrap();
let (r, d) = find_r_and_d(nsub1.clone());
'WitnessLoop: for kk in 0..6u64 {
let a = rand::thread_rng().gen_biguint_range(&two, &nsub1);
let mut x = mod_exp(&a, &d, &n);
if x == 1u64.to_biguint().unwrap() || x == nsub1 {
continue;
}
for rr in 1..r {
x = x.clone().mul(x.clone()).rem(n);
if x == 1u64.to_biguint().unwrap() {
return false;
} else if x == nsub1 {
continue 'WitnessLoop;
}
}
return false;
}
return true;
}
fn mod_exp(base: &BigUint, exponent: &BigUint, modulus: &BigUint) -> BigUint {
let one = 1u64.to_biguint().unwrap();
let mut result = one.clone();
let mut base_clone = base.clone();
let mut exponent_clone = exponent.clone();
while exponent_clone > 0u64.to_biguint().unwrap() {
if exponent_clone.clone() & one.clone() == one {
result = result.mul(&base_clone).rem(modulus);
}
base_clone = base_clone.clone().mul(base_clone).rem(modulus);
exponent_clone = exponent_clone.shr(1usize);
}
return result;
}
fn main() {
let now1 = now();
for n in 5u64..1_000_000u64 {
let b = n.to_biguint().unwrap();
if might_be_prime(&b) {
println!("{}", n);
}
}
let now2 = now();
println!("{}", now2.to_timespec().sec - now1.to_timespec().sec);
}
You can remove most of the clones pretty easily. BigUint has all ops traits implemented also for operations with &BigUint, not just working with values. With that, it becomes faster but still about half as fast as Java...
Also (not related to performance, just readability) you don't need to use add, sub, mul and shr explicitly; they override the regular +, -, * and >> operators.
For instance you could rewrite might_be_prime and mod_exp like this, which already gives a good speedup on my machine (from 40 to 24sec on avg):
fn might_be_prime(n: &BigUint) -> bool {
let one = BigUint::one();
let nsub1 = n - &one;
let two = BigUint::new(vec![2]);
let mut rng = rand::thread_rng();
let (r, mut d) = find_r_and_d(nsub1.clone());
let mut x;
let mut a: BigUint;
'WitnessLoop: for kk in 0..6u64 {
a = rng.gen_biguint_range(&two, &nsub1);
x = mod_exp(&mut a, &mut d, &n);
if &x == &one || x == nsub1 {
continue;
}
for rr in 1..r {
x = (&x * &x) % n;
if &x == &one {
return false;
} else if x == nsub1 {
continue 'WitnessLoop;
}
}
return false;
}
true
}
fn mod_exp(base: &mut BigUint, exponent: &mut BigUint, modulus: &BigUint) -> BigUint {
let one = BigUint::one();
let zero = BigUint::zero();
let mut result = BigUint::one();
while &*exponent > &zero {
if &*exponent & &one == one {
result = (result * &*base) % modulus;
}
*base = (&*base * &*base) % modulus;
*exponent = &*exponent >> 1usize;
}
result
}
Note that I've moved the println! out of the timing, so that we're not benchmarking IO.
fn main() {
let now1 = now();
let v = (5u64..1_000_000u64)
.filter_map(|n| n.to_biguint())
.filter(|n| might_be_prime(&n))
.collect::<Vec<BigUint>>();
let now2 = now();
for n in v {
println!("{}", n);
}
println!("time spent seconds: {}", now2.to_timespec().sec - now1.to_timespec().sec);
}
While writing the A* algorithm, I tried to reverse a singly-linked list of actions and pack it into Vec.
Here's the structure for my singly-linked list:
use std::rc::Rc;
struct FrontierElem<A> {
prev: Option<Rc<FrontierElem<A>>>,
action: A,
}
My first thought was to push actions into Vec then reverse the vector:
fn rev1<A>(fel: &Rc<FrontierElem<A>>) -> Vec<A>
where
A: Clone,
{
let mut cur = fel;
let mut ret = Vec::new();
while let Some(ref prev) = cur.prev {
ret.push(cur.action.clone());
cur = prev;
} // First action (where cur.prev==None) is ignored by design
ret.as_mut_slice().reverse();
ret
}
I didn't find the SliceExt::reverse method at the time, so I proceeded to the second plan: fill the vector from the end to the start. I didn't find a way to do that safely.
/// Copies action fields from single-linked list to vector in reverse order.
/// `fel` stands for first element
fn rev2<A>(fel: &Rc<FrontierElem<A>>) -> Vec<A>
where
A: Clone,
{
let mut cnt = 0usize;
// First pass. Let's find a length of list `fel`
{
let mut cur = fel;
while let Some(ref prev) = cur.prev {
cnt = cnt + 1;
cur = prev;
}
} // Lexical scoping to unborrow `fel`
// Second pass. Create and fill `ret` vector
let mut ret = Vec::<A>::with_capacity(cnt);
{
let mut idx = cnt - 1;
let mut cur = fel;
// I didn't find safe and fast way to populate vector from the end to the beginning.
unsafe {
ret.set_len(cnt); //unsafe. vector values aren't initialized
while let Some(ref prev) = cur.prev {
ret[idx] = cur.action.clone();
idx = idx - 1;
cur = prev;
}
}
assert_eq!(idx, std::usize::MAX);
} // Lexical scoping to make `fel` usable again
ret
}
While I was writing this, it occurred to me that I can also implement Iterator for the linked list and then use rev and from_iter to create a vector. Alas, this requires significant overhead, as I must implement DoubleEndedIterator trait for rev to work.
At this point my question seems trivial, but I post it in hope that it will be of some use.
Benchmark:
running 2 tests
test bench_rev1 ... bench: 1537061 ns/iter (+/- 14466)
test bench_rev2 ... bench: 1556088 ns/iter (+/- 17165)
Fill the vector, then reverse it using .as_mut_slice().reverse().
fn rev1<A>(fel: &Rc<FrontierElem<A>>) -> Vec<A>
where
A: Clone,
{
let mut cur = fel;
let mut ret = Vec::new();
while let Some(ref prev) = cur.prev {
ret.push(cur.action.clone());
cur = prev;
} // First action (where cur.prev==None) is ignored by design
ret.as_mut_slice().reverse();
ret
}