How to test a sleep function in golang - unit-testing

I have written my own sleep function and want to test it. Following is my code:
func TestSleep(t *testing.T) {
start := time.Now()
mySleepFunction(65)
end := time.Now()
if (end - start) != 65 {
t.Error("Incorrect sleep function")
}
}
This is not working. I am trying to get start time and end time and then compare it with expected time. The expected time will be in seconds. I tried end.Sub(start) but this returns me something like 1m30.0909, instead I need 90 as a result. It would be great if someone could help me.
Thanks :)

Elapsed time:
The easiest to get the elapsed time since a specific time (start) is to use the time.Since() function which returns a time.Duration which has a Duration.Seconds() method which returns the duration in seconds as float64.
So in your case the elapsed seconds:
sec := time.Since(start).Seconds()
Now on to testing...
When testing sleep-like functions you should take into consideration that after the sleep it is not guaranteed that the code will continue to execute immediately. For example quoting from the doc of time.Sleep():
Sleep pauses the current goroutine for at least the duration d.
So when writing test code for sleep-like functions, I would test like this:
elapsed time should be at least the specified,
and allow some error margin.
So for example test it like this:
func TestSleep(t *testing.T) {
const secSleep = 65.0
start := time.Now()
mySleepFunction(int(secSleep))
sec := time.Since(start).Seconds()
if sec < secSleep || sec > secSleep*1.05 {
t.Error("Incorrect sleep function")
}
}

If you use time.Unix() which gives you the amount of seconds since the epoch (January 1, 1970 UTC.) then your test should work.
func TestSleep(t *testing.T) {
start := time.Now().Unix()
mySleepFunction(65)
end := time.Now().Unix()
if (end - start) != 65{
t.Error("Incorrect sleep function")
}
}
Currently, your code is subtracting a time.Now() which doesn't return the result you intend. Your test wants simple int values that represent seconds.

Related

Get elapsed time just seconds in c++

I need to get the elapsed time from a while.
something.start()
auto start = std::chrono::steadyt_clock::now();
while(something->is_valid())
{
// getting frames
auto end = std::chrono::steady_clock::now();
auto diff = end - start;
// do something with the frames
if(diff % 3 == 0) { /* do something with the something */ }
}
But it get the time in every ms i get the time and my if statement runs too much. I can not use std::this_thread::sleep_for() cause i need every frame to catch. How can i do it pararell?
Since C++14 you could do diff >= 3s to see if the difference was equal or bigger than three seconds (see this duration literal reference).
Otherwise if you're stuck with C++11 then use diff >= std::chrono::seconds(3).
Note that this requires you to reset start each time the condition is true:
if (diff >= 3s)
{
start = end;
// Do something with the something...
}
This is required because the difference could stay equal to 3 (and therefore diff % 3s == 0 being true) for up to a whole second, which means your "Do something..." part will execute many times falsely.

issues concurrent queue in GCD in swift 3

i have an problem with GCD in swift 3
i create the concurrent queue and i pass function in this queue this function call another function
i need to print the elapsed time for each call
but i think the implementation is cut within the concurrent queue the following my code :
// peform task with the concurrent queue
class DoCalculations{
func doCalc() {
let x = 100
let y = x * x
_ = y / x
}
func performCalculation(itretion:Int,tag:String) {
let start = CFAbsoluteTimeGetCurrent()
for _ in 0..<itretion {
self.doCalc()
}
let end = CFAbsoluteTimeGetCurrent()
print("tag :\(tag) : \(end - start)")
}
}
let calc = DoCalculations()
let cQueue = DispatchQueue(label: "com.myCompany", attributes: .concurrent)
cQueue.async {
calc.performCalculation(itretion: 1000000, tag: "sync1")
}
cQueue.async {
calc.performCalculation(itretion: 1000, tag: "sync2")
}
cQueue.async {
calc.performCalculation(itretion: 100000, tag: "sync3")
}
// the print function is not Excuted
please can solve this issues
If you're doing this on a playground, you want to indicate that execution should continue "after the end of the playground’s top-level code is reached." You do this with needsIndefiniteExecution:
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
As the documentation for needsIndefiniteExecution says:
A Boolean value that indicates whether indefinite execution is enabled.
By default, all top-level code is executed, and then execution is terminated. When working with asynchronous code, enable indefinite execution to allow execution to continue after the end of the playground’s top-level code is reached. This, in turn, gives threads and callbacks time to execute.
Editing the playground automatically stops execution, even when indefinite execution is enabled.
Set needsIndefiniteExecution to true to continue execution after the end of top-level code. Set it to false to stop execution at that point.
The default value is false. It is set to true when liveView is set to a non-nil value.
Example of concurrent queue using gcd
func callGCDWithConcurrentQueue(){
let dispatchQueue = DispatchQueue(label: "Dmoe",qos:.utility,attributes: .concurrent)
dispatchQueue.async{ // Task 1
for i in 0...10{
print(i)
}
}
dispatchQueue.async{ //Task 2
for i in 10...20{
print(i)
}
}
}
callGCDWithConcurrentQueue() > // Calling Method
// OutPut
/
0
10
1
2
3
4
11
5
6
7
8
9
10
12
13
14
15
16
17
18
19
20
/

Pause function execute , in this time do nothing. c++

void PauseFor( int seconds)
{
clock_t temp;
temp = clock () + seconds * CLOCKS_PER_SEC ;
while (clock() < temp) {}
}
Ok, this is my function.
I want to make stop executing code for 2 seconds in this time do nothing.
Example:
RUN FUNCTION
after firs run , pause 2 seconds.
In this time 2 seconds do nothing.
after 2 seconds, you can run function again.
What i want to to ?
I want to stop using function for 2 seconds, In this time 2 seconds nothing happen..
Thanks :)
MyFunction()
{
//bla bla bla do something
PauseFor(2);
}
First run MyFunction() after first run , 2 seconds can't run.. after 2 seconds run again
Simply, a return false for 2 seconds
Try this
std::this_thread::sleep_for(std::chrono::seconds(2));

Go func closure in loop

When executing the following code I get what I expect when the first loop is done (sequence from 0 to 9). But when the second loop finishes, the result is not what I expected (I expected the same result as in the first loop, but it prints only '10's):
package main
import (
"fmt"
"sync"
)
func main() {
var wg sync.WaitGroup
for i := 0; i < 10; i++ {
wg.Add(1)
go func(j int) {
defer wg.Done()
fmt.Println(j)
}(i)
}
wg.Wait()
fmt.Println("done first")
for i := 0; i < 10; i++ {
wg.Add(1)
go func() {
defer wg.Done()
fmt.Println(i)
}()
}
wg.Wait()
fmt.Println("done second")
}
Output:
0
1
2
3
4
5
6
7
8
9
done first
10
10
10
10
10
10
10
10
10
10
done second
Why doesn't the second loop print a sequence?
Because the first one gets a copy of the loop counter each time. Whereas the second gets the variable captured as part of a closure.
In the first, you're passing it in here in every iteration of the loop:
go func(j int) {
defer wg.Done()
fmt.Println(j)
}(i) // <------------ its passed in here as part of each loop iteration
The second one receives nothing.. so, the loop counter i is captured as part of a closure. By the time the first go routine executes, the for loop has finished. The loop finishing has set the i variable (that is now part of a closure) to 10. Go routine #1 executes and prints the value of i.. which is now already 10 and the rest follow suit.
TLDR: The problem here is that the loop is finishing before any go routines are scheduled to be run - its just that quick. Therefore, i == 10 when the go routines run.

High-performance way to compile regular expressions in AS3?

I have a pretty simple question. What is the best (highest-performance/lowest memory-usage, etc.) way to compile a regular expression in AS3?
For instance, is this:
private var expression:RegExp = new RegExp(".*a$");
private function modify():void {
/* uses "expression" to chop up string */
}
Faster than this:
private var expression:RegExp = /.*a$/;
private function modify():void {
/* uses "expression" to chop up string */
}
Also, is there any real need to make the expression an instance variable if I'm only going to be using it once? For example, which of the following blocks of code would, in theory, perform faster:
private var myRegEx:RegExp = /\n/;
private function modify1():void {
myString.split(/\n/);
}
private function modify2():void {
myString.split(myRegEx);
}
Will modify1() run at the same execution speed as modify2()? I mean, does AS3 compile a new RegExp instance in modify1(), since it's not tied down to an instance variable?
Any help would be most appreciated :)
Your test is not very good. Here's why:
getTimer measures time, but cpu-time actually matters. If at some moment, for some reason the scheduler decides not to run the flash player, then you have less cpu-time within the same time frame. This is why results vary. It is the best you can use, but actually not much of a help if you're trying to track deviations of a few %.
The deviation is really small. About 8%. Part of it stems from the effect described in point 1. When I ran the tests, results did vary in fact. 8% can come from anywhere. They may even simply depend on your machine, OS or minor player version or whatever. The result is just not signifficant enough to rely on. Also 8% speedup is not really worth consideration unless you find, there's a horrible bottleneck in your string processing that can be fixed by this or that trick with RegExps
Most imporantly: the difference you measure has nothing to do with regular expressions, only with everything else in the test.
Let my explain this in detail.
Try public function test7():void{}. On my machine it takes about 30%-40% of the other tests. Let's have some numbers:
Running Tests
-------------------------------
Testing method: test1, 50000 iterations...
Test Complete.
Average Iteration Time: 0.01716ms
Longest Iteration Time: 5ms
Shortest Iteration Time: 0ms
Total Test Time: 901ms
-------------------------------
Testing method: test2, 50000 iterations...
Test Complete.
Average Iteration Time: 0.01706ms
Longest Iteration Time: 5ms
Shortest Iteration Time: 0ms
Total Test Time: 892ms
-------------------------------
Testing method: test3, 50000 iterations...
Test Complete.
Average Iteration Time: 0.01868ms
Longest Iteration Time: 5ms
Shortest Iteration Time: 0ms
Total Test Time: 969ms
-------------------------------
Testing method: test4, 50000 iterations...
Test Complete.
Average Iteration Time: 0.01846ms
Longest Iteration Time: 5ms
Shortest Iteration Time: 0ms
Total Test Time: 966ms
-------------------------------
Testing method: test5, 50000 iterations...
Test Complete.
Average Iteration Time: 0.01696ms
Longest Iteration Time: 5ms
Shortest Iteration Time: 0ms
Total Test Time: 890ms
-------------------------------
Testing method: test6, 50000 iterations...
Test Complete.
Average Iteration Time: 0.01696ms
Longest Iteration Time: 5ms
Shortest Iteration Time: 0ms
Total Test Time: 893ms
-------------------------------
Testing method: test7, 50000 iterations...
Test Complete.
Average Iteration Time: 0.00572ms
Longest Iteration Time: 1ms
Shortest Iteration Time: 0ms
Total Test Time: 306ms
-------------------------------
But Why? The following few things are expensive:
getTimer() call to global functions (and static methods of other classes) is slow
(tester[methodName] as Function).apply(); - this is expensive. A dynamic property access requiring a closure creation, then a cast to an anonymous function and then invocation through apply. I couldn't think of a slower way to call a function.
var tester:RegExpTester = new RegExpTester(); - instantiation is expensive, since it requires allocation and initialization.
the following code will run signifficantly better. The overhead measured by test7 is reduced by factor 20 on my machine:
private function test(methodName:String, iterations:int = 100):void {
output("Testing method: " + methodName + ", " + iterations + " iterations...");
var start:Number = getTimer();
var tester:RegExpTester = new RegExpTester();
var f:Function = tester[methodName];
for (var i:uint = 0; i < iterations; i++) f();//this call to f still is slower than the direct method call would be
var wholeTime:Number = getTimer() - start;
output("Test Complete.");
output("\tAverage Iteration Time: " + (wholeTime / iterations) + "ms");
output("\tTotal Test Time: " + wholeTime + "ms");
output("-------------------------------");
}
again, some numbers:
Running Tests
-------------------------------
Testing method: test1, 50000 iterations...
Test Complete.
Average Iteration Time: 0.01094ms
Total Test Time: 547ms
-------------------------------
Testing method: test2, 50000 iterations...
Test Complete.
Average Iteration Time: 0.01094ms
Total Test Time: 547ms
-------------------------------
Testing method: test3, 50000 iterations...
Test Complete.
Average Iteration Time: 0.01296ms
Total Test Time: 648ms
-------------------------------
Testing method: test4, 50000 iterations...
Test Complete.
Average Iteration Time: 0.01288ms
Total Test Time: 644ms
-------------------------------
Testing method: test5, 50000 iterations...
Test Complete.
Average Iteration Time: 0.01086ms
Total Test Time: 543ms
-------------------------------
Testing method: test6, 50000 iterations...
Test Complete.
Average Iteration Time: 0.01086ms
Total Test Time: 543ms
-------------------------------
Testing method: test7, 50000 iterations...
Test Complete.
Average Iteration Time: 0.00028ms
Total Test Time: 14ms
-------------------------------
so now the overhead is reduced to less than 1%, which makes it insignifficant (although in fact it can be reduced a lot more). However the deviation is now 16%. That's twice as much. And it's starting to look a little clearer. It is still insignifficant, IMHO, but actually it points to the two slowest methods: test3 and test4.
Why would that be? Simple: Both methods create a new RegExp object (one using a literal, the other using the constructor). This consumes the time difference we can measure. The difference is bigger now, since before, per iteration you created 3 regular expressions (the two instance variables are initialized every time you instantiate a RegExpTester). But the difference that is left now is that of creating 50000 RegExp instances. Anything else is about equally fast.
If there's a conclusion to be drawn in answer to your question: There is no difference between literals or constructed RegExps. So I am afraid, the answer is: "It doesn't really matter, as long as you keep general performance optimization rules in mind.". Hope that helps.
For the given scenario, I wrote a test class which gives me all the info I need on which type of regular expression to use:
package {
import flash.utils.getTimer;
import flash.text.TextFormat;
import flash.text.TextField;
import flash.display.Sprite;
public class RegExpTest extends Sprite {
private var textfield:TextField;
public function RegExpTest() {
this.textfield = new TextField();
this.textfield.x = this.textfield.y = 10;
this.textfield.width = stage.stageWidth - 20;
this.textfield.height = stage.stageHeight - 20;
this.textfield.defaultTextFormat = new TextFormat("Courier New");
this.addChild(textfield);
this.runtests();
}
private function runtests():void {
output("Running Tests");
output("-------------------------------");
test("test1", 50000);
test("test2", 50000);
test("test3", 50000);
test("test4", 50000);
test("test5", 50000);
test("test6", 50000);
}
private function test(methodName:String, iterations:int = 100):void {
output("Testing method: " + methodName + ", " + iterations + " iterations...");
var wholeTimeStart:Number = getTimer();
var iterationTimes:Array = [];
for (var i:uint = 0; i < iterations; i++) {
var iterationTimeStart:Number = getTimer();
var tester:RegExpTester = new RegExpTester();
// run method.
(tester[methodName] as Function).apply();
var iterationTimeEnd:Number = getTimer();
iterationTimes.push(iterationTimeEnd - iterationTimeStart);
}
var wholeTimeEnd:Number = getTimer();
var wholeTime:Number = wholeTimeEnd - wholeTimeStart;
var average:Number = 0;
var longest:Number = 0;
var shortest:Number = int.MAX_VALUE;
for each (var iteration:int in iterationTimes) {
average += iteration;
if (iteration > longest)
longest = iteration;
if (iteration < shortest)
shortest = iteration;
}
average /= iterationTimes.length;
output("Test Complete.");
output("\tAverage Iteration Time: " + average + "ms");
output("\tLongest Iteration Time: " + longest + "ms");
output("\tShortest Iteration Time: " + shortest + "ms");
output("\tTotal Test Time: " + wholeTime + "ms");
output("-------------------------------");
}
private function output(message:String):void {
this.textfield.appendText(message + "\n");
}
}
}
class RegExpTester {
private static const expression4:RegExp = /.*a$/;
private static const expression3:RegExp = new RegExp(".*a$");
private var value:String = "There is a wonderful man which is quite smelly.";
private var expression1:RegExp = new RegExp(".*a$");
private var expression2:RegExp = /.*a$/;
public function RegExpTester() {
}
public function test1():void {
var result:Array = value.split(expression1);
}
public function test2():void {
var result:Array = value.split(expression2);
}
public function test3():void {
var result:Array = value.split(new RegExp(".*a$"));
}
public function test4():void {
var result:Array = value.split(/.*a$/);
}
public function test5():void {
var result:Array = value.split(expression3);
}
public function test6():void {
var result:Array = value.split(expression4);
}
}
The results retrieved by running this example are as follows:
Running Tests
-------------------------------
Testing method: test1, 50000 iterations...
Test Complete.
Average Iteration Time: 0.0272ms
Longest Iteration Time: 23ms
Shortest Iteration Time: 0ms
Total Test Time: 1431ms
-------------------------------
Testing method: test2, 50000 iterations...
Test Complete.
Average Iteration Time: 0.02588ms
Longest Iteration Time: 5ms
Shortest Iteration Time: 0ms
Total Test Time: 1367ms
-------------------------------
Testing method: test3, 50000 iterations...
Test Complete.
Average Iteration Time: 0.0288ms
Longest Iteration Time: 5ms
Shortest Iteration Time: 0ms
Total Test Time: 1498ms
-------------------------------
Testing method: test4, 50000 iterations...
Test Complete.
Average Iteration Time: 0.0291ms
Longest Iteration Time: 5ms
Shortest Iteration Time: 0ms
Total Test Time: 1495ms
-------------------------------
Testing method: test5, 50000 iterations...
Test Complete.
Average Iteration Time: 0.02638ms
Longest Iteration Time: 5ms
Shortest Iteration Time: 0ms
Total Test Time: 1381ms
-------------------------------
Testing method: test6, 50000 iterations...
Test Complete.
Average Iteration Time: 0.02666ms
Longest Iteration Time: 10ms
Shortest Iteration Time: 0ms
Total Test Time: 1382ms
-------------------------------
Interesting to say the least. It seems that our spread really isn't too big and that the compiler is probably doing something behind the scenes to statically compile regular expressions. Food for thought.