Why does sorting take so long? - rust

I am currently trying to learn the syntax of Rust by solving little tasks. I compare the execution time as sanity-checks if I am using the language the right way.
One task is:
Create an array of 10000000 random integers in the range 0 - 1000000000
Sort it and measure the time
Print the time for sorting it
I got the following results:
| # | Language | Speed | LOCs |
| --- | -------------------- | ------ | ---- |
| 1 | C++ (with -O3) | 1.36s | 1 |
| 2 | Python (with PyPy) | 3.14s | 1 |
| 3 | Ruby | 5.04s | 1 |
| 4 | Go | 6.17s | 1 |
| 5 | C++ | 7.95s | 1 |
| 6 | Python (with Cython) | 11.51s | 1 |
| 7 | PHP | 36.28s | 1 |
Now I wrote the following Rust code:
rust.rs
extern crate rand;
extern crate time;
use rand::Rng;
use time::PreciseTime;
fn main() {
let n = 10000000;
let mut array = Vec::new();
let mut rng = rand::thread_rng();
for _ in 0..n {
//array[i] = rng.gen::<i32>();
array.push(rng.gen::<i32>());
}
// Sort
let start = PreciseTime::now();
array.sort();
let end = PreciseTime::now();
println!("{} seconds for sorting {} integers.", start.to(end), n);
}
with the following Cargo.toml:
[package]
name = "hello_world" # the name of the package
version = "0.0.1" # the current version, obeying semver
authors = [ "you#example.com" ]
[[bin]]
name = "rust"
path = "rust.rs"
[dependencies]
rand = "*" # Or a specific version
time = "*"
I compiled it with cargo run rust.rs and ran the binary. It outputs
PT18.207168155S seconds for sorting 10000000 integers.
Note that this is much slower than Python. I guess I am doing something wrong. (The complete code of rust and of the other languages is here if you are interested.)
Why does it take so long to sort with Rust? How can I make it faster?

I Tried your code on my computer, running it with cargo run gives:
PT11.634640178S seconds for sorting 10000000 integers.
And with cargo run --release (turning on optimizations) gives:
PT1.004434739S seconds for sorting 10000000 integers.

Related

Rust derive default on enum to remove need for impl block

~/Workspace/microscaler/docker-api-rs on fix/linting-issues cargo clippy --all-targets --all-features -- -D clippy::all -Z macro-backtrace ✔ at 20:14:11
Checking docker-api v0.12.2 (/Users/casibbald/Workspace/microscaler/docker-api-rs)
error: this `impl` can be derived
--> src/opts/container.rs:50:1
|
50 | / impl Default for Isolation {
51 | | fn default() -> Self {
52 | | Isolation::Default
53 | | }
54 | | }
| |_^
|
= help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#derivable_impls
= note: `-D clippy::derivable-impls` implied by `-D clippy::all`
= help: remove the manual implementation...
help: ...and instead derive it...
|
43 | #[derive(Default)]
|
help: ...and mark the default variant
|
45 ~ #[default]
46 ~ Default,
|
error: could not compile `docker-api` due to previous error
warning: build failed, waiting for other jobs to finish...
error: could not compile `docker-api` due to previous error
The following help page is referred to:
https://rust-lang.github.io/rust-clippy/master/index.html#derivable_impls
However, adding #[derive(Default)] does not seem so straightforward when multiple items exist.
Source code here:
https://github.com/microscaler/docker-api-rs/blob/d85deec98a10dcc2f6a1ed7c324010e28d437941/src/opts/container.rs#L50
The following does not work:
Checking docker-api v0.12.2 (/Users/casibbald/Workspace/microscaler/docker-api-rs)
error: no default declared
--> src/opts/container.rs:41:10
|
41 | #[derive(Default, Clone, Debug, Serialize, Deserialize)]
| ^^^^^^^ in this derive macro expansion
|
::: /Users/casibbald/.rustup/toolchains/nightly-aarch64-apple-darwin/lib/rustlib/src/rust/library/core/src/default.rs:186:1
|
186 | pub macro Default($item:item) {
| ----------------- in this expansion of `#[derive(Default)]`
|
= help: make a unit variant default by placing `#[default]` above it
Read the compiler/linter messages, they tell you exactly what to do:
= help: remove the manual implementation...
help: ...and instead derive it...
|
43 | #[derive(Default)]
|
help: ...and mark the default variant
|
45 ~ #[default]
46 ~ Default,
|
= help: make a unit variant default by placing `#[default]` above it
Like this:
#[derive(Default, Clone, Debug)]
pub enum Isolation {
#[default]
Default,
Process,
HyperV,
}

rust-sqlx: Lazy instance has previously been poisoned

I'm trying to run cargo fix on a project that uses slqx and am getting the following error:
error: proc macro panicked
--> src/twitter/domain/user.rs:54:5
|
54 | / sqlx::query!(
55 | | r#"
56 | | INSERT INTO users
57 | | (id, created_at,
... |
84 | | user["public_metrics"]["tweet_count"].as_i64(),
85 | | )
| |_____^
|
= help: message: Lazy instance has previously been poisoned
= note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)
...for every instance of sqlx macro I have in my code. The weird thing is it used to work just fine, but for some reason doesn't anymore.
The only mention of the error on Google that I found is here, but I don't think it's relevant.
What might be wrong?

build failed in substrate.dev Ink! tutorial. sp-aritmetic lack of type? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
My build has failed.
Everything looked good up until I tested my contract with the command:
cargo +nightly test
I got error [E0282]
Here is the whole error report:
error[E0282]: type annotations needed
--> /home/mal/.cargo/registry/src/github.com-1ecc6299db9ec823/sp-arithmetic-2.0.0/src/fixed_point.rs:541:9
|
541 | let accuracy = P::ACCURACY.saturated_into();
| ^^^^^^^^ consider giving `accuracy` a type
...
1595 | / implement_fixed!(
1596 | | FixedI64,
1597 | | test_fixed_i64,
1598 | | i64,
... |
1601 | | "_Fixed Point 64 bits signed, range = [-9223372036.854775808, 9223372036.854775807]_",
1602 | | );
| |__- in this macro invocation
|
= note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)
error[E0282]: type annotations needed
--> /home/mal/.cargo/registry/src/github.com-1ecc6299db9ec823/sp-arithmetic-2.0.0/src/fixed_point.rs:541:9
|
541 | let accuracy = P::ACCURACY.saturated_into();
| ^^^^^^^^ consider giving `accuracy` a type
...
1604 | / implement_fixed!(
1605 | | FixedI128,
1606 | | test_fixed_i128,
1607 | | i128,
... |
1611 | | [-170141183460469231731.687303715884105728, 170141183460469231731.687303715884105727]_",
1612 | | );
| |__- in this macro invocation
|
= note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)
error[E0282]: type annotations needed
--> /home/mal/.cargo/registry/src/github.com-1ecc6299db9ec823/sp-arithmetic-2.0.0/src/fixed_point.rs:541:9
|
541 | let accuracy = P::ACCURACY.saturated_into();
| ^^^^^^^^ consider giving `accuracy` a type
...
1614 | / implement_fixed!(
1615 | | FixedU128,
1616 | | test_fixed_u128,
1617 | | u128,
... |
1621 | | [0.000000000000000000, 340282366920938463463.374607431768211455]_",
1622 | | );
| |__- in this macro invocation
|
= note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)
error: aborting due to 3 previous errors
For more information about this error, try `rustc --explain E0282`.
error: could not compile `sp-arithmetic`
This is part of a wider tutorial.
I believe rust is updated.
The problem seems to be the macro sp-aritmetic, however I am not sure how to give it a "type". My rust is non-existent...
Really eager to get into Ink! so any help is appreciated.
The cause of that error is a regression in the rust nightly compiler starting with version 2020-10-06. You need to rustup toolchain install 2020-10-05 and use that one for building your runtime until this issue is resolved. Usually, the latest nightly is automatically used to build your runtime. You can override this behaviour by setting the WASM_BUILD_TOOLCHAIN environment variable. In this case:
export WASM_BUILD_TOOLCHAIN='nightly-2020-10-05'
In case of building a contract with cargo contract you should use:
cargo +nightly-2020-10-05 contract build

Detect VP8 Key Frame(I-Frame) in RTP stream

I need to detect VP8 Key Frame in RTP packet. I know how to remove RTP header and get the payload.
Does it have a specific signature/header?
There is an RFC for VP8 which explains how to do detect if a frame is a key frame. See section 19.1.
| Frame Tag | Type |
| ------------------------------------------------- | ----- |
| frame_tag | f(24) |
| if (key_frame) { | |
| start_code | f(24) |
| horizontal_size_code | f(16) |
| vertical_size_code | f(16) |
| } | |
The 3-byte frame tag can be parsed as follows:
---- Begin code block --------------------------------------
unsigned char *c = pbi->source;
unsigned int tmp;
tmp = (c[2] << 16) | (c[1] << 8) | c[0];
key_frame = tmp & 0x1;
version = (tmp >> 1) & 0x7;
show_frame = (tmp >> 4) & 0x1;
first_part_size = (tmp >> 5) & 0x7FFFF;
---- End code block ----------------------------------------

How to include modules for code coverage for unit testing?

My assumption is that any module tested using Intern will automatically be covered by Istanbul's code coverage. For reasons unknown to me, my module is not being included.
I am:
running Intern 1.6.2 (installed with npm locally)
testing NodeJS code
using callbacks, not promises
using CommonJS modules, not AMD modules
Directory Structure (only showing relevant files):
plister
|
|--libraries
| |--file-type-support.js
|
|--tests
| |--intern.js
| |--unit
| |--file-type-support.js
|
|--node_modules
|--intern
plister/tests/intern.js
define({
useLoader: {
'host-node': 'dojo/dojo'
},
loader: {
packages: [
{name: 'libraries', location: 'libraries'}
]
},
reporters: ['console'],
suites: ['tests/unit/file-type-support'],
functionalSuites: [],
excludeInstrumentation: /^(tests|node_modules)\//
});
plister/tests/unit/file-type-support.js
define([
'intern!bdd',
'intern/chai!expect',
'intern/dojo/node!fs',
'intern/dojo/node!path',
'intern/dojo/node!stream-equal',
'intern/dojo/node!../../libraries/file-type-support'
], function (bdd, expect, fs, path, streamEqual, fileTypeSupport) {
'use strict';
bdd.describe('file-type-support', function doTest() {
bdd.it('should show that the example output.plist matches the ' +
'temp.plist generated by the module', function () {
var deferred = this.async(),
input = path.normalize('tests/resources/input.plist'),
output = path.normalize('tests/resources/output.plist'),
temporary = path.normalize('tests/resources/temp.plist');
// Test deactivate function by checking output produced by
// function against test output.
fileTypeSupport.deactivate(fs.createReadStream(input),
fs.createWriteStream(temporary),
deferred.rejectOnError(function onFinish() {
streamEqual(fs.createReadStream(output),
fs.createReadStream(temporary),
deferred.callback(function checkEqual(error, equal) {
expect(equal).to.be.true;
}));
}));
});
});
});
Output:
PASS: main - file-type-support - should show that the example output.plist matches the temp.plist generated by the module (29ms)
1/1 tests passed
1/1 tests passed
Output (on failure):
FAIL: main - file-type-support - should show that the example output.plist matches the temp.plist generated by the module (30ms)
AssertionError: expected true to be false
AssertionError: expected true to be false
0/1 tests passed
0/1 tests passed
npm ERR! Test failed. See above for more details.
npm ERR! not ok code 0
Output (after removing excludeInstrumentation):
PASS: main - file-type-support - should show that the example output.plist matches the temp.plist generated by the module (25ms)
1/1 tests passed
1/1 tests passed
------------------------------------------+-----------+-----------+-----------+-----------+
File | % Stmts |% Branches | % Funcs | % Lines |
------------------------------------------+-----------+-----------+-----------+-----------+
node_modules/intern/ | 70 | 50 | 100 | 70 |
chai.js | 70 | 50 | 100 | 70 |
node_modules/intern/lib/ | 79.71 | 42.86 | 72.22 | 79.71 |
Test.js | 79.71 | 42.86 | 72.22 | 79.71 |
node_modules/intern/lib/interfaces/ | 80 | 50 | 63.64 | 80 |
bdd.js | 100 | 100 | 100 | 100 |
tdd.js | 76.19 | 50 | 55.56 | 76.19 |
node_modules/intern/lib/reporters/ | 56.52 | 35 | 57.14 | 56.52 |
console.js | 56.52 | 35 | 57.14 | 56.52 |
node_modules/intern/node_modules/chai/ | 37.9 | 8.73 | 26.38 | 39.34 |
chai.js | 37.9 | 8.73 | 26.38 | 39.34 |
tests/unit/ | 100 | 100 | 100 | 100 |
file-type-support.js | 100 | 100 | 100 | 100 |
------------------------------------------+-----------+-----------+-----------+-----------+
All files | 42.14 | 11.35 | 33.45 | 43.63 |
------------------------------------------+-----------+-----------+-----------+-----------+
My module passes the test and I can make it fail too. It just will not show up in the code coverage. I have done the tutorial hosted on GitHub without any problems.
I tried dissecting the Istanbul and Intern dependencies. I place a console.log where it seems files to be covered go through, but my module doesn't get passed. I have tried every variation of deferred.callback and deferred.rejectOnError with no difference to the code coverage.
Also, any feedback on my use of deferred.callback and deferred.rejectOnError will be greatly appreciated. I am still a little uncertain on their usage.
Thanks!
As of Intern 1.6, only require('vm').runInThisContext is hooked to add code coverage data, not require. Instrumentation of require was added in Intern 2.0.
The use of callback/rejectOnError in the above code is correct.

Resources