fn missing_number(nums: &[u32]) -> u32 { (0..=nums.len() as u32).find(|n| !nums.contains(&n)).unwrap() }
class Solution {public:int missingNumber(vector<int>& nums) {}};- fn missing_number(nums: &[u32]) -> u32 {
- (0..=nums.len() as u32).find(|n| !nums.contains(&n)).unwrap()
- }
#[test] fn test() { assert_eq!(missing_number(&[0, 1, 2, 3, 4, 6, 7, 8, 9]), 5); assert_eq!(missing_number(&[0, 1, 3, 4]), 2); assert_eq!(missing_number(&[1, 2, 3, 4, 5]), 0); assert_eq!(missing_number(&[0, 1, 2, 3, 4]), 5); assert_eq!(missing_number(&[0]), 1); assert_eq!(missing_number(&[1]), 0); }
#include <criterion/criterion.h>// Function to find the missing number in an array of integersint findMissingNumber(int arr[], int n) {// Code to find the missing number- #[test]
- fn test() {
- assert_eq!(missing_number(&[0, 1, 2, 3, 4, 6, 7, 8, 9]), 5);
- assert_eq!(missing_number(&[0, 1, 3, 4]), 2);
- assert_eq!(missing_number(&[1, 2, 3, 4, 5]), 0);
- assert_eq!(missing_number(&[0, 1, 2, 3, 4]), 5);
- assert_eq!(missing_number(&[0]), 1);
- assert_eq!(missing_number(&[1]), 0);
- }
Test(findMissingNumber, should_return_5_for_given_array) {int arr[] = {1, 2, 3, 4, 6, 7, 8, 9, 10};int n = sizeof(arr) / sizeof(arr[0]);cr_assert_eq(findMissingNumber(arr, n), 5);}Test(findMissingNumber, should_return_2_for_given_array) {int arr[] = {1, 3, 4, 5};int n = sizeof(arr) / sizeof(arr[0]);cr_assert_eq(findMissingNumber(arr, n), 2);}
fn split(string: &str, separator: char) -> Vec<&str> { string.split(separator).collect() }
#include <string>#include <sstream>#include <vector>auto split(const std::string& str, char sep) {auto result = std::vector<std::string>{};auto stream = std::stringstream(str);auto buffer = std::string{};while (std::getline(stream, buffer, sep)) result.emplace_back(buffer);return result;- fn split(string: &str, separator: char) -> Vec<&str> {
- string.split(separator).collect()
- }
#[test] fn test() { assert_eq!(split("Hello World", ' '), ["Hello", "World"]); assert_eq!(split("John-brings-his-cat", '-'), ["John", "brings", "his", "cat"]); }
// TODO: Replace examples and use TDD by writing your own testsDescribe(any_group_name_you_want){It(should_do_something){Assert::That(split("Hello World", ' '), Equals(std::vector<std::string>{"Hello", "World"}));Assert::That(split("John-brings-his-cat", '-'), Equals(std::vector<std::string>{"John","brings","his","cat"}));}};- #[test]
- fn test() {
- assert_eq!(split("Hello World", ' '), ["Hello", "World"]);
- assert_eq!(split("John-brings-his-cat", '-'), ["John", "brings", "his", "cat"]);
- }
fn mean(x: &[u64]) -> u64 { x.iter().sum::<u64>() / x.len() as u64 }
#include <iostream>double Mean(double x[], int n){double sum = 0;for(int i = 0; i < n; i++){sum += x[i];}return sum / n;}- fn mean(x: &[u64]) -> u64 {
- x.iter().sum::<u64>() / x.len() as u64
- }
#[test] fn test() { assert_eq!(mean(&[4, 8, 4, 8]), 6); }
// TODO: Replace examples and use TDD by writing your own testsDescribe(any_group_name_you_want){It(should_do_something){int n = 4;double x[] = {4,8,4,8};double mean;mean = Mean(x ,n);Assert::That(6, Equals(mean));}};- #[test]
- fn test() {
- assert_eq!(mean(&[4, 8, 4, 8]), 6);
- }
fn total_fine(speed: i32, signals: &[i32]) -> u32 { signals.iter().map(|&signal| fine(speed, signal)).sum() } fn fine(speed: i32, signal: i32) -> u32 { match speed - signal { ..=9 => 0, 10..=19 => 100, 20..=29 => 250, 30.. => 500 } }
public class Kata {public static int speedLimit(int speed, int[] signals) {int penalty = 0;for (int i = 0; i < signals.length; i++){if (speed > signals[i]){if (speed - signals[i] >= 30){penalty += 500;} else if (speed - signals[i] >= 20 && speed - signals[i] < 30){penalty += 250;} else if (speed - signals[i] >= 10 && speed - signals[i] < 20){penalty += 100;}}}return penalty;- fn total_fine(speed: i32, signals: &[i32]) -> u32 {
- signals.iter().map(|&signal| fine(speed, signal)).sum()
- }
- fn fine(speed: i32, signal: i32) -> u32 {
- match speed - signal {
- ..=9 => 0,
- 10..=19 => 100,
- 20..=29 => 250,
- 30.. => 500
- }
- }
#[cfg(test)] mod tests { use super::*; #[test] fn test_add() { assert_eq!(total_fine(70, &[]), 0); assert_eq!(total_fine(60, &[80, 70, 60]), 0); assert_eq!(total_fine(0, &[15, 25, 35, 46]), 0); assert_eq!(total_fine(100, &[110, 100, 80]), 250); assert_eq!(total_fine(130, &[140, 130, 100]), 500); } }
import org.junit.jupiter.api.Test;import static org.junit.jupiter.api.Assertions.assertEquals;- #[cfg(test)]
- mod tests {
- use super::*;
// TODO: Replace examples and use TDD by writing your own testsclass SolutionTest {@Testvoid testSomething() {// assertEquals("expected", "actual");- #[test]
- fn test_add() {
- assert_eq!(total_fine(70, &[]), 0);
- assert_eq!(total_fine(60, &[80, 70, 60]), 0);
- assert_eq!(total_fine(0, &[15, 25, 35, 46]), 0);
- assert_eq!(total_fine(100, &[110, 100, 80]), 250);
- assert_eq!(total_fine(130, &[140, 130, 100]), 500);
- }
- }
Optimized for conciseness
use itertools::Itertools; fn print(number: u64) -> u64 { number.to_string().chars().sorted().rev().collect::<String>().parse().unwrap() }
fn print(mut number: u64) -> u64 {let mut digits = Vec::new();while number > 0 {digits.push(number % 10);number /= 10;}digits.sort();digits.into_iter().rev().fold(0, |result, digit| result * 10 + digit)- use itertools::Itertools;
- fn print(number: u64) -> u64 {
- number.to_string().chars().sorted().rev().collect::<String>().parse().unwrap()
- }
Optimized for speed
fn print(mut number: u64) -> u64 { let mut digits = Vec::new(); while number > 0 { digits.push(number % 10); number /= 10; } digits.sort(); digits.into_iter().rev().fold(0, |result, digit| result * 10 + digit) }
import java.util.Arrays;public class MaxNumber {public static long print(long number) {return number- fn print(mut number: u64) -> u64 {
- let mut digits = Vec::new();
- while number > 0 {
- digits.push(number % 10);
- number /= 10;
- }
- digits.sort();
- digits.into_iter().rev().fold(0, |result, digit| result * 10 + digit)
- }
#[test] fn test() { assert_eq!(print(4), 4); assert_eq!(print(12), 21); assert_eq!(print(101), 110); assert_eq!(print(400000005000007000), 754000000000000000); assert_eq!(print(307778062924466824), 988777666444322200); }
import static org.junit.Assert.assertEquals;import org.junit.Test;import java.util.Random;public class MaxNumberTest {@Testpublic void testFour() {assertEquals(4, MaxNumber.print(4));}@Testpublic void testTwelve() {assertEquals(21, MaxNumber.print(12));}@Testpublic void testOneHundred() {assertEquals(110, MaxNumber.print(101));}@Testpublic void testHuge1() {assertEquals(754000000000000000L, MaxNumber.print(400000005000007000L));}@Testpublic void testHuge2() {assertEquals(988777666444322200L, MaxNumber.print(307778062924466824L));}- #[test]
- fn test() {
- assert_eq!(print(4), 4);
- assert_eq!(print(12), 21);
- assert_eq!(print(101), 110);
- assert_eq!(print(400000005000007000), 754000000000000000);
- assert_eq!(print(307778062924466824), 988777666444322200);
- }
struct Test { a: Option<String>, b: Option<String>, } impl Test { fn new() -> Self { Self { a: Default::default(), b: None, } } }
namespace Test {public class Test {public string a;public string b = null;}- struct Test {
- a: Option<String>,
- b: Option<String>,
- }
- impl Test {
- fn new() -> Self {
- Self {
- a: Default::default(),
- b: None,
- }
- }
- }
#[test] fn test() { let test = Test::new(); assert_eq!(test.a, test.b); }
namespace Solution {using NUnit.Framework;using System;using Test;[TestFixture]public class SolutionTest{[Test]public void MyTest(){var test = new Test();Assert.AreEqual(test.a, test.b);}}}- #[test]
- fn test() {
- let test = Test::new();
- assert_eq!(test.a, test.b);
- }
fn find_max(array: &[i32]) -> i32 { *array.iter().max().unwrap() }
public class Kata {public static int findMax(int[] my_array) {// Write a method that returns the largest integer in the list.// You can assume that the list has at least one element.return 7;}}- fn find_max(array: &[i32]) -> i32 {
- *array.iter().max().unwrap()
- }
#[test] fn test() { assert_eq!(find_max(&[4, 5, 6, 7]), 7); }
import org.junit.jupiter.api.Test;import static org.junit.jupiter.api.Assertions.assertEquals;// TODO: Write more tests to prove your code bleowclass SolutionTest {@Testvoid testSomething() {assertEquals(Kata.findMax(new int[]{4, 5, 6, 7}), 7);}- #[test]
- fn test() {
- assert_eq!(find_max(&[4, 5, 6, 7]), 7);
- }
fn get_nth_words(string: &str, n: usize) -> String { if n == 0 { return String::new() } string.split(" ").skip(n - 1).step_by(n).collect::<Vec<_>>().join(" ") }
def get_nth_words(string, n):if n < 1: return ""return ' '.join(['',*string.split()][::n][1:])- fn get_nth_words(string: &str, n: usize) -> String {
- if n == 0 { return String::new() }
- string.split(" ").skip(n - 1).step_by(n).collect::<Vec<_>>().join(" ")
- }
#[cfg(test)] mod tests { use super::get_nth_words; #[test] fn basic_tests() { assert_eq!(get_nth_words("Hello World", 2), "World"); assert_eq!(get_nth_words("1 2 3 4 5 6 7 8 9", 3), "3 6 9"); assert_eq!(get_nth_words("Lorem ipsum dolor sit amet", 1), "Lorem ipsum dolor sit amet"); assert_eq!(get_nth_words("And a one and a two and a three and a four", 3), "one two three four"); } #[test] fn not_enough_words() { assert_eq!(get_nth_words("There aren't enough words.", 5), ""); assert_eq!(get_nth_words("What if there weren't enough words?", 15), ""); assert_eq!(get_nth_words("What are the chances of there being enough words?", 150), ""); assert_eq!(get_nth_words("", 5000), ""); } #[test] fn attempt_errors() { assert_eq!(get_nth_words("", 1), ""); assert_eq!(get_nth_words("error 1 2 3 4", 0), ""); } }
import codewars_test as test- #[cfg(test)]
- mod tests {
- use super::get_nth_words;
- #[test]
- fn basic_tests() {
- assert_eq!(get_nth_words("Hello World", 2), "World");
- assert_eq!(get_nth_words("1 2 3 4 5 6 7 8 9", 3), "3 6 9");
- assert_eq!(get_nth_words("Lorem ipsum dolor sit amet", 1), "Lorem ipsum dolor sit amet");
- assert_eq!(get_nth_words("And a one and a two and a three and a four", 3), "one two three four");
- }
- #[test]
- fn not_enough_words() {
- assert_eq!(get_nth_words("There aren't enough words.", 5), "");
- assert_eq!(get_nth_words("What if there weren't enough words?", 15), "");
- assert_eq!(get_nth_words("What are the chances of there being enough words?", 150), "");
- assert_eq!(get_nth_words("", 5000), "");
- }
from solution import get_nth_wordsbasictests = [["Hello World", 2, "World"],["1 2 3 4 5 6 7 8 9", 3, "3 6 9"],["Lorem ipsum dolor sit amet", 1, "Lorem ipsum dolor sit amet"],["And a one and a two and a three and a four", 3, "one two three four"]]notenoughwords = [["There aren't enough words.", 5, ""],["What if there weren't enough words?", 15, ""],["What are the chances of there being enough words?", 150, ""],["", 5000, ""]]attempterrors = [["", 1, ""],["error 1 2 3 4", 0, ""],["Hmm... What about this?", -1, ""],["", -5, ""]]@test.describe("Basic Tests")def basic_test_group():@test.it("Basic Tests")def basic_tests():for tst in basictests:test.assert_equals(get_nth_words(tst[0], tst[1]), tst[2])@test.it("Not Enough Words")def not_enough_words():for tst in notenoughwords:test.assert_equals(get_nth_words(tst[0], tst[1]), tst[2])@test.it("Exception Handling")def cause_errors():for tst in attempterrors:test.assert_equals(get_nth_words(tst[0], tst[1]), tst[2])- #[test]
- fn attempt_errors() {
- assert_eq!(get_nth_words("", 1), "");
- assert_eq!(get_nth_words("error 1 2 3 4", 0), "");
- }
- }
fn find_multiples(base: usize, limit: usize) -> Vec<usize> { (base..=limit).step_by(base).collect() }
def find_multiples(b, l):a=[]for i in range(b,l+1,b):a.append(i)return a- fn find_multiples(base: usize, limit: usize) -> Vec<usize> {
- (base..=limit).step_by(base).collect()
- }
#[test] fn test() { assert_eq!(find_multiples(5, 25), [5, 10, 15, 20, 25]); assert_eq!(find_multiples(1, 2), [1, 2]); assert_eq!(find_multiples(6, 30), [6, 12, 18, 24, 30]); }
import codewars_test as testfrom solution import find_multiples@test.describe("Fixed Tests")def fixed_tests():@test.it('Basic Test Cases')def basic_test_cases():test.assert_equals(find_multiples(5, 25), [5, 10, 15, 20, 25])test.assert_equals(find_multiples(1, 2), [1, 2])test.assert_equals(find_multiples(6, 30), [6, 12, 18, 24, 30])- #[test]
- fn test() {
- assert_eq!(find_multiples(5, 25), [5, 10, 15, 20, 25]);
- assert_eq!(find_multiples(1, 2), [1, 2]);
- assert_eq!(find_multiples(6, 30), [6, 12, 18, 24, 30]);
- }
Manually checked lock. Contains unsafe and is most likely to be unsound since I'm still learning concurrency.
use std::{thread, sync::atomic::{AtomicBool, Ordering::*}}; fn count() -> u32 { let lock = AtomicBool::new(false); let count = 0; thread::scope(|s| { for _ in 0..10 { s.spawn(|| { for _ in 0..100 { while lock.compare_exchange(false, true, Acquire, Relaxed).is_err() {} let count_ptr = &count as *const u32 as *mut u32; unsafe { *count_ptr += 1; } lock.store(false, Release); } }); } }); count }
use std::{thread, sync::atomic::{AtomicU32, Ordering::Relaxed}};- use std::{thread, sync::atomic::{AtomicBool, Ordering::*}};
- fn count() -> u32 {
let count = AtomicU32::new(0);- let lock = AtomicBool::new(false);
- let count = 0;
- thread::scope(|s| {
- for _ in 0..10 {
- s.spawn(|| {
- for _ in 0..100 {
let current = count.load(Relaxed);count.store(current + 1, Relaxed);- while lock.compare_exchange(false, true, Acquire, Relaxed).is_err() {}
- let count_ptr = &count as *const u32 as *mut u32;
- unsafe { *count_ptr += 1; }
- lock.store(false, Release);
- }
- });
- }
- });
count.into_inner()- count
- }
use std::time::Instant; #[test] fn test_count() { let start = Instant::now(); for _ in 0..10_000 { assert_eq!(count(), 1_000); } let elapsed = start.elapsed(); println!("{}ms", elapsed.as_millis()); }
- use std::time::Instant;
- #[test]
- fn test_count() {
- let start = Instant::now();
- for _ in 0..10_000 {
- assert_eq!(count(), 1_000);
- }
- let elapsed = start.elapsed();
- println!("{}ms", elapsed.as_millis());
- }
Seems like it should be worse than an atomic since there's additional overhead, but isn't notably slower.
use std::{thread, sync::Mutex}; fn count() -> u32 { let count = Mutex::new(0); thread::scope(|s| { for _ in 0..10 { s.spawn(|| { for _ in 0..100 { *count.lock().unwrap() += 1; } }); } }); count.into_inner().unwrap() }
use std::{thread, sync::atomic::{AtomicU32, Ordering::Relaxed}};- use std::{thread, sync::Mutex};
- fn count() -> u32 {
let count = AtomicU32::new(0);- let count = Mutex::new(0);
- thread::scope(|s| {
- for _ in 0..10 {
- s.spawn(|| {
- for _ in 0..100 {
let current = count.load(Relaxed);count.store(current + 1, Relaxed);- *count.lock().unwrap() += 1;
- }
- });
- }
- });
count.into_inner()- count.into_inner().unwrap()
- }
use std::time::Instant; #[test] fn test_count() { let start = Instant::now(); for _ in 0..10_000 { assert_eq!(count(), 1_000); } let elapsed = start.elapsed(); println!("{}ms", elapsed.as_millis()); }
- use std::time::Instant;
- #[test]
- fn test_count() {
- let start = Instant::now();
- for _ in 0..10_000 {
- assert_eq!(count(), 1_000);
- }
- let elapsed = start.elapsed();
- println!("{}ms", elapsed.as_millis());
- }
Feels kinda like cheating. Surprisingly not faster. Maybe the thread spawning dominates the runtime anyways?
use std::{thread, sync::atomic::{AtomicU32, Ordering::Relaxed}}; fn count() -> u32 { let global_count = AtomicU32::new(0); thread::scope(|s| { for _ in 0..10 { s.spawn(|| { let mut local_count = 0; for _ in 0..100 { local_count += 1; } global_count.fetch_add(local_count, Relaxed); }); } }); global_count.into_inner() }
- use std::{thread, sync::atomic::{AtomicU32, Ordering::Relaxed}};
- fn count() -> u32 {
let count = AtomicU32::new(0);- let global_count = AtomicU32::new(0);
- thread::scope(|s| {
- for _ in 0..10 {
- s.spawn(|| {
- let mut local_count = 0;
- for _ in 0..100 {
let current = count.load(Relaxed);count.store(current + 1, Relaxed);- local_count += 1;
- }
- global_count.fetch_add(local_count, Relaxed);
- });
- }
- });
count.into_inner()- global_count.into_inner()
- }
use std::time::Instant; #[test] fn test_count() { let start = Instant::now(); for _ in 0..10_000 { assert_eq!(count(), 1_000); } let elapsed = start.elapsed(); println!("{}ms", elapsed.as_millis()); }
- use std::time::Instant;
- #[test]
- fn test_count() {
- let start = Instant::now();
- for _ in 0..10_000 {
- assert_eq!(count(), 1_000);
- }
- let elapsed = start.elapsed();
- println!("{}ms", elapsed.as_millis());
- }
fn encode(string: &str) -> String { string.chars().map(|ch| { match ch { 'a' => '1', 'e' => '2', 'i' => '3', 'o' => '4', 'u' => '5', _ => ch } }).collect() } fn decode(string: &str) -> String { string.chars().map(|ch| { match ch { '1' => 'a', '2' => 'e', '3' => 'i', '4' => 'o', '5' => 'u', _ => ch } }).collect() }
function encode(string){return [...string].map(el => {return ( "aeiou".includes(el))? "aeiou".indexOf(el) + 1 : el}).join('')}- fn encode(string: &str) -> String {
- string.chars().map(|ch| {
- match ch {
- 'a' => '1',
- 'e' => '2',
- 'i' => '3',
- 'o' => '4',
- 'u' => '5',
- _ => ch
- }
- }).collect()
- }
function decode(string){return [...string].map(el => {return ("12345".includes(el)) ? {'1':"a","2":"e","3":"i","4":"o","5":"u"}[el] : el}).join('')}- fn decode(string: &str) -> String {
- string.chars().map(|ch| {
- match ch {
- '1' => 'a',
- '2' => 'e',
- '3' => 'i',
- '4' => 'o',
- '5' => 'u',
- _ => ch
- }
- }).collect()
- }
#[cfg(test)] mod tests { use super::{encode, decode}; #[test] fn encode_vowels() { assert_eq!(encode("hello"), "h2ll4"); assert_eq!(encode("codewars"), "c4d2w1rs"); assert_eq!(encode("a"), "1"); assert_eq!(encode("e"), "2"); assert_eq!(encode("i"), "3"); assert_eq!(encode("o"), "4"); assert_eq!(encode("u"), "5"); } #[test] fn ignore_consonants() { assert_eq!(encode("bcdfghjklmnpqrstvwxyz"), "bcdfghjklmnpqrstvwxyz"); assert_eq!(decode("bcdfghjklmnpqrstvwxyz"), "bcdfghjklmnpqrstvwxyz"); } #[test] fn decode_digits() { assert_eq!(decode("h2ll4"), "hello"); assert_eq!(decode("c4d2w1rs"), "codewars"); assert_eq!(decode("1"), "a"); assert_eq!(decode("2"), "e"); assert_eq!(decode("3"), "i"); assert_eq!(decode("4"), "o"); assert_eq!(decode("5"), "u"); } #[test] fn ignore_other_digits() { assert_eq!(decode("67890"), "67890"); } #[test] fn empty_string() { assert_eq!(encode(""), ""); assert_eq!(decode(""), ""); } #[test] fn mixed_letters() { assert_eq!(encode("hello world"), "h2ll4 w4rld"); assert_eq!(decode("h2ll4 w4rld"), "hello world"); } #[test] fn ignore_already_transformed() { assert_eq!(encode("h2ll4"), "h2ll4"); assert_eq!(decode("codewarsaei"), "codewarsaei"); } }
// Since Node 10, we're using Mocha.// You can use `chai` for assertions.const chai = require("chai");const assert = chai.assert;// Uncomment the following line to disable truncating failure messages for deep equals, do:// chai.config.truncateThreshold = 0;// Since Node 12, we no longer include assertions from our deprecated custom test framework by default.// Uncomment the following to use the old assertions:// const Test = require("@codewars/test-compat");- #[cfg(test)]
- mod tests {
- use super::{encode, decode};
describe("Solution", function() {it("should test for something", function() {// Test.assertEquals(1 + 1, 2);// assert.strictEqual(1 + 1, 2);});});- #[test]
- fn encode_vowels() {
- assert_eq!(encode("hello"), "h2ll4");
- assert_eq!(encode("codewars"), "c4d2w1rs");
- assert_eq!(encode("a"), "1");
- assert_eq!(encode("e"), "2");
- assert_eq!(encode("i"), "3");
- assert_eq!(encode("o"), "4");
- assert_eq!(encode("u"), "5");
- }
- #[test]
- fn ignore_consonants() {
- assert_eq!(encode("bcdfghjklmnpqrstvwxyz"), "bcdfghjklmnpqrstvwxyz");
- assert_eq!(decode("bcdfghjklmnpqrstvwxyz"), "bcdfghjklmnpqrstvwxyz");
- }
- #[test]
- fn decode_digits() {
- assert_eq!(decode("h2ll4"), "hello");
- assert_eq!(decode("c4d2w1rs"), "codewars");
- assert_eq!(decode("1"), "a");
- assert_eq!(decode("2"), "e");
- assert_eq!(decode("3"), "i");
- assert_eq!(decode("4"), "o");
- assert_eq!(decode("5"), "u");
- }
- #[test]
- fn ignore_other_digits() {
- assert_eq!(decode("67890"), "67890");
- }
- #[test]
- fn empty_string() {
- assert_eq!(encode(""), "");
- assert_eq!(decode(""), "");
- }
- #[test]
- fn mixed_letters() {
- assert_eq!(encode("hello world"), "h2ll4 w4rld");
- assert_eq!(decode("h2ll4 w4rld"), "hello world");
- }
- #[test]
- fn ignore_already_transformed() {
- assert_eq!(encode("h2ll4"), "h2ll4");
- assert_eq!(decode("codewarsaei"), "codewarsaei");
- }
- }
The simple fix. Runtime around 3 seconds for 10000 calls.
use std::{thread, sync::atomic::{AtomicU32, Ordering::Relaxed}}; fn count() -> u32 { let count = AtomicU32::new(0); thread::scope(|s| { for _ in 0..10 { s.spawn(|| { for _ in 0..100 { count.fetch_add(1, Relaxed); } }); } }); count.into_inner() }
- use std::{thread, sync::atomic::{AtomicU32, Ordering::Relaxed}};
- fn count() -> u32 {
- let count = AtomicU32::new(0);
- thread::scope(|s| {
- for _ in 0..10 {
- s.spawn(|| {
- for _ in 0..100 {
let current = count.load(Relaxed);count.store(current + 1, Relaxed);- count.fetch_add(1, Relaxed);
- }
- });
- }
- });
- count.into_inner()
- }
use std::time::Instant; #[test] fn test_count() { let start = Instant::now(); for _ in 0..10_000 { assert_eq!(count(), 1_000); } let elapsed = start.elapsed(); println!("{}ms", elapsed.as_millis()); }
- use std::time::Instant;
- #[test]
- fn test_count() {
- let start = Instant::now();
- for _ in 0..10_000 {
- assert_eq!(count(), 1_000);
- }
- let elapsed = start.elapsed();
- println!("{}ms", elapsed.as_millis());
- }