I wanted to check how best to optimize my main project, and decided to check which implementation is faster. But I always get different results.
time for point.x += 0.1 = 5.7182994, 2097152
time for point.set_x(point.get_x() + 0.1) = 5.599908, 2097152
time for temp += 0.1 and point.set_x(temp) = 5.562349, 2097152
time for temp += 0.1 and point.x = temp = 6.4794574, 2097152
time for point.x += 0.1 = 5.83212, 2097152
time for point.set_x(point.get_x() + 0.1) = 5.5968776, 2097152
time for temp += 0.1 and point.set_x(temp) = 5.594217, 2097152
time for temp += 0.1 and point.x = temp = 5.5190163, 2097152
time for point.x += 0.1 = 5.6057734, 2097152
time for point.set_x(point.get_x() + 0.1) = 5.5254517, 2097152
time for temp += 0.1 and point.set_x(temp) = 5.528735, 2097152
time for temp += 0.1 and point.x = temp = 5.5161138, 2097152
time for point.x += 0.1 = 5.5781226, 2097152
time for point.set_x(point.get_x() + 0.1) = 5.6262784, 2097152
time for temp += 0.1 and point.set_x(temp) = 5.5054255, 2097152
time for temp += 0.1 and point.x = temp = 5.69275, 2097152
Which implementation is faster?
Code
use std::time::Instant;
trait ObjectInterface {
fn get_x(&self) -> f32;
fn set_x(&mut self, x: f32);
}
struct Point {
x: f32,
_y: f32
}
impl ObjectInterface for Point{
fn get_x(&self) -> f32 {
self.x
}
fn set_x(&mut self, x: f32) {
self.x = x;
}
}
fn add_one_million_time() {
let mut point: Point = Point {
x: 0.0,
_y: 0.0
};
let now = Instant::now();
// for _ in -2147483648..=2147483647 {
for _ in -2147483648..=2147483647 {
point.x += 0.1;
}
// }
println!("time for point.x += 0.1 = {}, {}", Instant::now().duration_since(now).as_secs_f32(), point.x);
point.x = 0.0;
let now = Instant::now();
// for _ in -2147483648..=2147483647 {
for _ in -2147483648..=2147483647 {
point.set_x(point.get_x() + 0.1);
}
// }
println!("time for point.set_x(point.get_x() + 0.1) = {}, {}", Instant::now().duration_since(now).as_secs_f32(), point.x);
point.x = 0.0;
let now = Instant::now();
let mut temp: f32 = point.get_x();
// for _ in -2147483648..=2147483647 {
for _ in -2147483648..=2147483647 {
temp += 0.1;
}
// }
point.set_x(temp);
println!("time for temp += 0.1 and point.set_x(temp) = {}, {}", Instant::now().duration_since(now).as_secs_f32(), point.x);
point.x = 0.0;
let now = Instant::now();
let mut temp: f32 = point.x;
// for _ in -2147483648..=2147483647 {
for _ in -2147483648..=2147483647 {
temp += 0.1;
}
// }
point.x = temp;
println!("time for temp += 0.1 and point.x = temp = {}, {}", Instant::now().duration_since(now).as_secs_f32(), point.x);
}
fn main() {
add_one_million_time()
}