Skip to contentSkip to conversation

CodeSamples: Switch ARM64 get_timestamp() to use the hardware counter

PATCH Applied Elad Lahav 2 participants 3 messages Aug 16, 2022

lore
Share & tools
lore

Elad Lahav

author
#0 lore raw

PATCH 2/2 CodeSamples: Switch ARM64 get_timestamp() to use the hardware counter

---
 CodeSamples/arch-arm64/arch-arm64.h | 15 ++-------------
 1 file changed, 2 insertions(+), 13 deletions(-)
CodeSamples/arch-arm64/arch-arm64.h +2 -13
index f45d8bdc..220b8b16 100644
@@ -43,24 +43,13 @@
 #define smp_mb()  __asm__ __volatile__("dmb ish" : : : "memory")
 
 
-#include <stdlib.h>
-#include <time.h>
-
-#ifndef CLOCK_MONOTONIC_RAW
-#define CLOCK_MONOTONIC_RAW CLOCK_MONOTONIC
-#endif
-
 /*
  * Generate 64-bit timestamp.
  */
-static __inline__ unsigned long long get_timestamp(void)
+static inline unsigned long long get_timestamp(void)
 {
 	unsigned long long thetime;
-	struct timespec tv;
 
-	if (clock_gettime(CLOCK_MONOTONIC_RAW, &tv) != 0)
-		return 0;
-	thetime = ((unsigned long long)tv.tv_sec) * 1000000000ULL +
-		  ((unsigned long long)tv.tv_nsec);
+	__asm__ __volatile__ ("isb; mrs %0, cntvct_el0" : "=r"(thetime));
 	return thetime;
 }
Signature · 1 line
2.25.1
author
#1 lore raw
Quoted 1 line · Elad Lahav

I tested the change on an aarch64 board on both QNX and Linux. The Linux results show quite the change in performance from the clock_gettime() version, which is probably expected.

Before:

root@localhost:~/src/CodeSamples/defer# ./gettimestamp
d3f5e50a7d
d3f5e50af5 120
d3f5e50b6d 120
d3f5e50be5 120
d3f5e50c5d 120
d3f5e50cd5 120
d3f5e50d25 80
d3f5e50d9d 120
d3f5e50e15 120
d3f5e50e8d 120

After:

root@localhost:~/src/CodeSamples/defer# ./gettimestamp
73706dac1
73706dac2 1
73706dac4 2
73706dac5 1
73706dac6 1
73706dac8 2
73706dac9 1
73706dacb 2
73706dacc 1
73706dacd 1

--Elad

#2 lore raw
Quoted 2 lines · Elad Lahav
Quoted 1 line · Elad Lahav

Queued and pushed, thank you!

Quoted 18 lines

I tested the change on an aarch64 board on both QNX and Linux. The Linux results show quite the change in performance from the clock_gettime() version, which is probably expected.

Before:

root@localhost:~/src/CodeSamples/defer# ./gettimestamp
d3f5e50a7d
d3f5e50af5 120
d3f5e50b6d 120
d3f5e50be5 120
d3f5e50c5d 120
d3f5e50cd5 120
d3f5e50d25 80
d3f5e50d9d 120
d3f5e50e15 120
d3f5e50e8d 120

After:

Quoted 11 lines
root@localhost:~/src/CodeSamples/defer# ./gettimestamp
73706dac1
73706dac2 1
73706dac4 2
73706dac5 1
73706dac6 1
73706dac8 2
73706dac9 1
73706dacb 2
73706dacc 1
73706dacd 1

I have to ask... Are these the same units? (I have in the past used hardware where they would not be.)

Anyway, even if the hardware clock ticks an order of magnitude more slowly, it is an impressive speedup. ;-)

Thanx, Paul