Created
May 18, 2014 23:38
-
-
Save repeatedly/cd31eef8647bf585f3d4 to your computer and use it in GitHub Desktop.
scope(exit) overhead in dlang. See http://lk4d4.darth.io/posts/defer/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Why
putWithScope
is faster thanput
?I will check generated code...