Skip to content

Instantly share code, notes, and snippets.

@azat
Created December 20, 2023 19:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save azat/158b9e5a718d30c5a5a475c51222f895 to your computer and use it in GitHub Desktop.
Save azat/158b9e5a718d30c5a5a475c51222f895 to your computer and use it in GitHub Desktop.
#include <bits/time.h>
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <time.h>
// https://igoro.com/archive/gallery-of-processor-cache-effects/
u_int64_t now_ns()
{
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC_RAW, &ts);
return ts.tv_sec * (uint64_t)1e9 + ts.tv_nsec;
}
__inline__ uint64_t rdtsc(void)
{
uint32_t lo, hi;
__asm__ __volatile__ ( // serialize
"xorl %%eax,%%eax \n cpuid"
::: "%rax", "%rbx", "%rcx", "%rdx");
/* We cannot use "=A", since this would use %rax on x86_64 and return only the lower 32bits of the TSC */
__asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
return (uint64_t)hi << 32 | lo;
}
#define N (1024*1024*64)
int main()
{
int * array = calloc(sizeof(int), N);
for (size_t k = 0; k < 4; ++k)
{
uint64_t start = rdtsc();
for (size_t i = 0; i < N; i += 1)
{
array[i] *= 3;
}
uint64_t end = rdtsc();
printf("elapsed: %lu\n", end - start);
}
free(array);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment