add time.perf_counter

This commit is contained in:
blueloveTH 2025-09-11 18:14:15 +08:00
parent 5657989e27
commit 8f6ab9f436

View File

@ -20,9 +20,7 @@
return nanos; return nanos;
} }
#else #else
int64_t time_ns() { int64_t time_ns() { return 0; }
return 0;
}
#endif #endif
static bool time_time(int argc, py_Ref argv) { static bool time_time(int argc, py_Ref argv) {
@ -39,15 +37,21 @@ static bool time_time_ns(int argc, py_Ref argv) {
return true; return true;
} }
static bool time_perf_counter(int argc, py_Ref argv) {
PY_CHECK_ARGC(0);
py_newfloat(py_retval(), (double)clock() / CLOCKS_PER_SEC);
return true;
}
static bool time_sleep(int argc, py_Ref argv) { static bool time_sleep(int argc, py_Ref argv) {
PY_CHECK_ARGC(1); PY_CHECK_ARGC(1);
py_f64 secs; py_f64 secs;
if(!py_castfloat(argv, &secs)) return false; if(!py_castfloat(argv, &secs)) return false;
int64_t start = time_ns(); clock_t start = clock();
const int64_t end = start + secs * 1000000000; const clock_t end = start + (clock_t)(secs * CLOCKS_PER_SEC);
while(true) { while(true) {
int64_t now = time_ns(); clock_t now = clock();
if(now >= end) break; if(now >= end) break;
} }
py_newnone(py_retval()); py_newnone(py_retval());
@ -101,6 +105,7 @@ void pk__add_module_time() {
py_bindfunc(mod, "time", time_time); py_bindfunc(mod, "time", time_time);
py_bindfunc(mod, "time_ns", time_time_ns); py_bindfunc(mod, "time_ns", time_time_ns);
py_bindfunc(mod, "perf_counter", time_perf_counter);
py_bindfunc(mod, "sleep", time_sleep); py_bindfunc(mod, "sleep", time_sleep);
py_bindfunc(mod, "localtime", time_localtime); py_bindfunc(mod, "localtime", time_localtime);
} }