Skip to content

Instantly share code, notes, and snippets.

@richinseattle
Last active August 26, 2019 06:35
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save richinseattle/78e40e36e3215d1ff26eb1d39c0580e1 to your computer and use it in GitHub Desktop.
Save richinseattle/78e40e36e3215d1ff26eb1d39c0580e1 to your computer and use it in GitHub Desktop.
#include <Windows.h>
#include <time.h>
#include <string>
using namespace std;
#define BTF_FLAG 0x300
#define TRAP_FLAG 0x100
LONG CALLBACK TraceCallback(LPEXCEPTION_POINTERS ex)
{
switch (ex->ExceptionRecord->ExceptionCode)
{
case STATUS_SINGLE_STEP:
ex->ContextRecord->Dr7 |= BTF_FLAG;
ex->ContextRecord->EFlags |= TRAP_FLAG;
return EXCEPTION_CONTINUE_EXECUTION;
default:
return EXCEPTION_CONTINUE_SEARCH;
}
}
void InitTrace()
{
AddVectoredExceptionHandler(TRUE, TraceCallback);
RaiseException(STATUS_SINGLE_STEP, 0, 0, 0);
}
bool IsPrimeSlow(int num)
{
for (int i = 2; i < num; i++)
if (num % i == 0) return false;
return true;
}
int main(int argc, char **argv)
{
UNREFERENCED_PARAMETER(argv);
if (argc > 1)
{
printf("Activating BTF trace\n");
InitTrace();
}
else
printf("Trace disabled this run, pass any argument to activate it\n");
time_t start;
double diff = 0;
int count = 0;
int max_num = 100000;
printf("Finding Primes between 1 and %d.. \n", max_num);
start = time(NULL);
for(int i = 1; i <= max_num; i++)
if(IsPrimeSlow(i)) count++;
diff = difftime(time(NULL), start);
printf("\nFound %d prime numbers between 1 and %d in %f seconds\n", count, max_num, diff);
return 0;
}
// native: Found 25812 prime numbers between 1 and 297534 in 15.000000 seconds
// BTF: Found 952 prime numbers between 1 and 7508 in 15.000000 seconds
// 27x slowdown
// IntelPT: Found 24288 prime numbers between 1 and 278120 in 15.000000 seconds
// 1.05x
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment