From 3595a0c9ec2afc62633c4f0e47fd85c9f630a448 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Henrik=20Tj=C3=A4der?= <henrik@tjaders.com>
Date: Mon, 20 Nov 2017 17:44:33 +0100
Subject: [PATCH] Fixed the critical section so can use DWT

---
 README.md   |  5 +++++
 src/main.rs | 29 ++++++++++++++++++++++++-----
 2 files changed, 29 insertions(+), 5 deletions(-)

diff --git a/README.md b/README.md
index 92f8a99..32e401e 100644
--- a/README.md
+++ b/README.md
@@ -51,3 +51,8 @@ PLAIN however is mutable and will be changed on the "return" of decode()
 Currently there is only one function so it should be safe, however, with
 two tasks this would not be the case. In a typical microcontroller setting
 with interrupt handlers it would be similar "safe" like C.
+
+## Debug vs Release analysis
+
+Time taken to decode ABC is `Decoded in 4457 cycles`,
+while in release mode this is reduced to `Decoded in 338 cycles`.
diff --git a/src/main.rs b/src/main.rs
index 6c2013b..dba99d0 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -3,14 +3,16 @@
 
 extern crate cortex_m_semihosting;
 extern crate stm32f40x;
+extern crate cortex_m;
 
 use core::fmt::Write;
 
 use cortex_m_semihosting::hio;
 
-//use std::str::from_utf8;
 use core::str::from_utf8;
 
+use stm32f40x::{DWT};
+
 static ABC: [u32; 4] = [0x9fdd9158,
                         0x85715808,
                         0xac73323a,
@@ -252,13 +254,30 @@ fn main() {
     // get a handle to the *host* standard output
     let mut stdout = hio::hstdout().unwrap();
 
-    writeln!(stdout, "Time to decode!").unwrap();
+    // Critical section
+    cortex_m::interrupt::free(
+        |cs| {
+
+            // Enable the DWT CYCCNT
+            let dwt = DWT.borrow(cs);
+            dwt.enable_cycle_counter();
+
+            writeln!(stdout, "Time to decode!").unwrap();
+
+            let mut seed = 0x0e0657c1;
+
+            //writeln!(stdout, "current counter:\n {:?}", dwt.cyccnt.read()).unwrap();
 
-    let mut seed = 0x0e0657c1;
+            let before = dwt.cyccnt.read();
+            decode(&ABC, unsafe { &mut PLAIN }, &mut seed);
+            //decode(&CODED, unsafe { &mut PLAIN }, &mut seed);
+            let after = dwt.cyccnt.read();
+            writeln!(stdout, "Decoded in {} cycles", after-before).unwrap();
 
-    decode(&CODED, unsafe { &mut PLAIN }, &mut seed);
+            writeln!(stdout, "Decoded:\n {:#?}", from_utf8(unsafe { &PLAIN }).unwrap()).unwrap();
 
-    writeln!(stdout, "Decoded:\n {:#?}", from_utf8(unsafe { &PLAIN }).unwrap()).unwrap();
+        }
+    );
 
     /*
     let mut locseed;
-- 
GitLab