对于最小循环的枚举,Python 3似乎比Python 2的速度要慢得多,而对于新版本的Python 3,这似乎越来越差.
我在我的64位Windows机器上安装了Python 2.7.6,Python 3.3.3和Python 3.4.0(Intel i7-2700K - 3.5 GHz),每个Python都安装了32位和64位版本.虽然对于给定版本,在存储器访问限制内,32位和64位之间的执行速度没有显着差异,但不同版本级别之间存在非常显着的差异.我会让时间结果说明如下:
C:\**Python34_64**\python -mtimeit -n 5 -r 2 -s"cnt = 0" "for i in range(10000000): cnt += 1"
5 loops, best of 2: **900 msec** per loop
C:\**Python33_64**\python -mtimeit -n 5 -r 2 -s"cnt = 0" "for i in range(10000000): cnt += 1"
5 loops, best of 2: **820 msec** per loop
C:\**Python27_64**\python -mtimeit -n 5 -r 2 -s"cnt = 0" "for i in range(10000000): cnt += 1"
5 loops, …Run Code Online (Sandbox Code Playgroud) 在实现 LazyList 的一个版本(一个不可变的延迟计算的记忆单链表,就像 Haskell 列表)时,我遇到了一个实现问题,IntoIterator因为代码在我认为应该删除引用时却没有删除。以下代码已被简化,只是为了显示问题;因此,它不是通用的,也不包括与实现无关的所有方法IntoIterator:
use std::cell::UnsafeCell;
use std::mem::replace;
use std::rc::Rc;
// only necessary because Box<FnOnce() -> R> doesn't yet work...
trait Invoke<R = ()> {
fn invoke(self: Box<Self>) -> R;
}
impl<'a, R, F: 'a + FnOnce() -> R> Invoke<R> for F {
#[inline(always)]
fn invoke(self: Box<F>) -> R {
(*self)()
}
}
// not thread safe
struct Lazy<'a, T: 'a>(UnsafeCell<LazyState<'a, T>>);
enum LazyState<'a, T: 'a> {
Unevaluated(Box<Invoke<T> + 'a>),
EvaluationInProgress,
Evaluated(T),
}
use self::LazyState::*; …Run Code Online (Sandbox Code Playgroud) 我最近阅读了有关大量数字的更快的Eratosthenes分段筛网实施方案的信息。
以下是相同的实现:
function sieve(low, high) {
var primeArray = [], ll = Math.sqrt(low), output = [];
for (var i = 0; i < high; i++) {
primeArray[i] = true;
}
for (var i = 2; i <= ll; i++) {
if (primeArray[i]) {
for (var j = i * i; j < high; j += i) {
primeArray[j] = false;
}
}
}
for (var i = 2; i < ll; i++) {
if(primeArray[i])
{
var segmentStart = Math.floor(low/i) * …Run Code Online (Sandbox Code Playgroud) 进一步IntoIterator按照Rust的书实现包装矢量的示例,我还尝试根据以下代码(Playground链接)实现IntoIterator以引用包装器:
struct VecWrapper(Vec<i32>);
impl VecWrapper {
fn iter(&'static self) -> Iter {
Iter(Box::new(self.0.iter()))
}
}
struct Iter(Box<Iterator<Item = &'static i32>>);
impl Iterator for Iter {
type Item = &'static i32;
fn next(&mut self) -> Option<Self::Item> {
self.0.next()
}
}
impl IntoIterator for &'static VecWrapper {
type Item = &'static i32;
type IntoIter = Iter;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
fn main() {
// let test = vec![1, 2, 3]; // …Run Code Online (Sandbox Code Playgroud) lifetime ×2
rust ×2
borrowing ×1
iterator ×1
javascript ×1
loops ×1
performance ×1
primes ×1
python ×1
python-2.7 ×1
python-3.x ×1
sieve ×1