Skip to content

Instantly share code, notes, and snippets.

@repeatedly
Created May 18, 2014 23:38
Show Gist options
  • Save repeatedly/cd31eef8647bf585f3d4 to your computer and use it in GitHub Desktop.
Save repeatedly/cd31eef8647bf585f3d4 to your computer and use it in GitHub Desktop.
scope(exit) overhead in dlang. See http://lk4d4.darth.io/posts/defer/
import std.array;
import std.stdio;
import std.datetime;
import core.sync.mutex;
final class Queue
{
private:
Mutex _mutex;
int[] _arr;
public:
this()
{
_mutex = new Mutex();
}
void put(int e)
{
_mutex.lock();
_arr ~= e;
_mutex.unlock();
}
void putWithScope(int e)
{
_mutex.lock();
scope(exit) _mutex.unlock();
_arr ~= e;
}
int get()
{
_mutex.lock();
if (_arr.empty) {
_mutex.unlock();
return 0;
}
int r = _arr.front;
_arr.popFront();
_mutex.unlock();
return r;
}
int getWithScope()
{
_mutex.lock();
scope(exit) _mutex.unlock();
if (_arr.empty) {
return 0;
}
int r = _arr.front;
_arr.popFront();
return r;
}
}
immutable N = 1000;
void putBench()
{
auto q1 = new Queue();
auto q2 = new Queue();
void put()
{
foreach (_; 0..N) {
foreach (j; 0..1000) {
q1.put(j);
}
}
}
void putWithScope()
{
foreach (_; 0..N) {
foreach (j; 0..1000) {
q2.putWithScope(j);
}
}
}
auto r = benchmark!(put, putWithScope)(10);
writeln("put: ", r[0].msecs);
writeln("putWithScope: ", r[1].msecs);
}
void getBench()
{
auto q1 = new Queue();
auto q2 = new Queue();
foreach (i; 0..1000) {
q1.put(i);
q2.put(i);
}
void get()
{
foreach (_; 0..N) {
foreach (j; 0..2000) {
q1.get();
}
}
}
void getWithScope()
{
foreach (_; 0..N) {
foreach (j; 0..2000) {
q2.getWithScope();
}
}
}
auto r = benchmark!(get, getWithScope)(10);
writeln("get: ", r[0].msecs);
writeln("getWithScope: ", r[1].msecs);
}
void main()
{
putBench();
getBench();
}
@repeatedly
Copy link
Author

Why putWithScope is faster than put?

% dmd -inline -O -release -run scope_bench.d
put: 807
putWithScope: 785
get: 779
getWithScope: 791

I will check generated code...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment