Michael Brooks | fe2b2a8 | 2024-03-29 17:34:32 +0000 | [diff] [blame] | 1 | /* |
| 2 | * Copyright 2024 Google LLC |
| 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
| 16 | |
| 17 | #ifndef BENCHMARKS_CYCLE_COUNT_H_ |
| 18 | #define BENCHMARKS_CYCLE_COUNT_H_ |
| 19 | |
| 20 | inline uint64_t mcycle_read(void) { |
| 21 | uint32_t cycle_low = 0; |
| 22 | uint32_t cycle_high = 0; |
| 23 | uint32_t cycle_high_2 = 0; |
| 24 | asm volatile( |
| 25 | "1:" |
| 26 | " csrr %0, mcycleh;" // Read `mcycleh`. |
| 27 | " csrr %1, mcycle;" // Read `mcycle`. |
| 28 | " csrr %2, mcycleh;" // Read `mcycleh` again. |
| 29 | " bne %0, %2, 1b;" |
| 30 | : "=r"(cycle_high), "=r"(cycle_low), "=r"(cycle_high_2) |
| 31 | :); |
| 32 | return static_cast<uint64_t>(cycle_high) << 32 | cycle_low; |
| 33 | } |
| 34 | |
| 35 | #endif // #ifndef BENCHMARKS_CYCLE_COUNT_H_ |