Skip to content

Instantly share code, notes, and snippets.

Avatar

Graham King grahamking

View GitHub Profile
@grahamking
grahamking / runperf
Last active Jul 28, 2022
Bash script to run a benchmark under decent conditons.
View runperf
#!/bin/bash
#
# Usage: runperf ./my-benchmark-binary
#
# Script to run a benchmark / performance test in decent conditions. Based on:
# - https://www.llvm.org/docs/Benchmarking.html
# - "Performance Analysis and Tuning on Modern CPU" by Denis Bakhvalov, Appendix A.
# - https://github.com/andikleen/pmu-tools
#
# Note that this doesn't do any actual benchmarking, your binary must be able to do that all by itself.
@grahamking
grahamking / errs.go
Created May 22, 2020
Collect and handle multiple errors in Go
View errs.go
package util
import (
"errors"
"strings"
)
// Errs is an error that collects other errors, for when you want to do
// several things and then report all of them.
type Errs struct {
View ps-read.rs
use std::error::Error;
use std::io::{stdin, Read};
use std::time;
fn main() -> Result<(), Box<dyn Error>> {
let mut v: Vec<u8> = vec![0; 65536];
let mut howmany = 0;
let s = stdin();
let mut cin = s.lock();
let mut n = 1;
@grahamking
grahamking / main.rs
Created Jun 5, 2021
Memory ordering experiment in Rust. See https://preshing.com/20120515/memory-reordering-caught-in-the-act/ . Try changing the two HERE lines.
View main.rs
// 1. Run it as is (SeqCst). Should be just timing output
// 2. Change the two HERE lines to Ordering::Relaxed and run it again.
// That should give lots of (seemingly impossible) memory reorderings.
use rand;
use std::sync::atomic::{AtomicU8, Ordering};
use std::sync::*;
use std::thread;
fn main() {
@grahamking
grahamking / slicemap_test.go
Created Jun 30, 2015
Benchmark comparing map access vs slice search
View slicemap_test.go
package main
import (
"math/rand"
"testing"
"time"
)
const (
numItems = 100 // change this to see how number of items affects speed
View trait_operator.rs
struct Sponge {
name: String,
}
impl std::ops::Add for Sponge {
type Output = Self;
fn add(self, other: Self) -> Self {
Sponge {
name: self.name + "X" + &other.name,
}
View trait_overload2.rs
trait Position<T> {
fn pos(&self) -> T;
}
struct Location {
lat: f32,
lon: f32,
}
impl Position<String> for Location {
View trait_overload1.rs
trait Nameable<T> {
fn set_name(&mut self, T);
}
struct Cyborg{
name: Option<String>,
}
impl Nameable<&str> for Cyborg {
fn set_name(&mut self, s: &str) {
View trait_mixin2.rs
trait SurelyNot {
fn can_we_build_it(&self);
}
impl SurelyNot for String {
fn can_we_build_it(&self) {
println!("Yes we can");
}
}
fn main() {
View trait_mixin1.rs
struct StdoutLogger {}
impl std::fmt::Display for StdoutLogger {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
writeln!(f, "I am StdoutLogger")
}
}
fn main() {
let l = StdoutLogger {};