9. Thời gian thực thi lệnh
9.1 Tính thời gian thực thi lệnh
Nếu bạn muốn biết thời gian máy tính đã sử dụng để thực thi một đoạn mã, bạn sử dụng dụng khối lệnh có tên là timer.
Cách thức sử dụng như sau:
Một đoạn mã tham khảo:
Bài tập 9a. Cho bạn mèo thực hiện làm toán thử thách: lấy 1 tới 1 000 000, lần lượt nhân với 2. Đọc ra kết quả của mỗi phép nhân. Tính thử xem bạn mèo làm xong thử thách này hết bao nhiêu thời gian.
9.1 Timing
Sometimes we need to know how long it takes to execute a piece of code. We can use the timer block for this. To measure the time we use the variable t.
Start: memorize the start time in t
End: subtract the start time t from the current time
9.2 Read more …
The animation loop
Loops in Scratch are slowed down to allow simple animation. Let’s measure the time to repeat a move block 10 times. The total time is 0.32 seconds. Thus the loop time is 32 ms which results roughly in 30 frames per second.
Empty loop
How long does it take to repeat an empty loop 10 times? The time is too small to be measured. Even if we increase it to 1000 times, the measured time still shows 0. We need to repeat the loop 1 million times, to be able to measure something. It takes a total time of 1.2 seconds. Thus executing the empty loop takes only 1.2 us.
When adding a set to block the time increases to 2 us. We conclude that the set to block alone takes 0.8 us.
The change by block takes the same amount of time, roughly 0.8 us.
Math operation
When putting the add block inside the set to block the loop execution time becomes 3 us. Thus we conclude the add block takes 1 us.
String operation
A simple string operation takes roughly the same time as a math operation. Accessing an indexed letter in a string takes 1.2 us.
Resolution of the timer
What is the resolution of the timer? Does it have a micro-second resolution?
In fact, now. The Scratch timer is a VERY low resolution timer. To measure its resolution, we record all timer values in a list.