时间与空间编程主要涉及如何高效地处理时间和空间资源。以下是一些基本的概念和示例代码:
获取当前时间
C语言
```c
include include int main() { time_t timer; struct tm *tblock; timer = time(NULL); tblock = localtime(&timer); printf("Local time is: %s", asctime(tblock)); return 0; } ``` C++ ```cpp include include include int main() { auto now = std::chrono::system_clock::now(); time_t time = std::chrono::system_clock::to_time_t(now); std::cout << "Current time: " << std::ctime(&time); return 0; } ``` Python ```python import datetime now = datetime.datetime.now() print("Current time:", now) ``` 时间计算 C语言 ```c include include int main() { time_t time1 = time(NULL); double sum = 0; for (int i = 0; i < 1000000000; i++) { sum += sqrt(i); } printf("Sum of square roots: %f\n", sum); return 0; } ``` C++ ```cpp include include include int main() { auto start = std::chrono::high_resolution_clock::now(); double sum = 0; for (int i = 0; i < 1000000000; i++) { sum += std::sqrt(i); } auto end = std::chrono::high_resolution_clock::now(); std::chrono::duration std::cout << "Sum of square roots: " << sum << "\nTime elapsed: " << elapsed.count() << " seconds\n"; return 0; } ``` 空间换时间 C语言 ```c include int fibonacci(int n) { int fArry = {1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040, 1346269, 2178309, 3524578, 5702887, 9227465, 14930352, 24157817, 39088169, 63245986, 102334155, 165580141}; if (n <= 1) { return 1; } return fArry[n]; } int main() { int n = 40; printf("Fibonacci number at position %d is %d\n", n, fibonacci(n)); return 0; } ``` C++